<?php

/**
 * Implements hook_help().
 */
function tweetbutton_help($path, $arg) {
  switch ($path) {
    case 'admin/help#tweetbutton':
    case 'admin/config/services/tweetbutton':
      $output = '';
      $output .= '<h3>' . t('About') . '</h3>';
      $output = '<p>' . t('This button allows your website to let people share content on Twitter without having to leave the page. Promote strategic Twitter accounts at the same time while driving traffic to your website. These are the general configuration options for the button.') . '</p>';
      $output .= '<p>' . t('To add tweetbutton you have to create a tweetbutton field and add it to your content (node, taxonomy, user).') . '</p>';
      return $output;
  }
}

/**
 * Implementation of hook_field_info() 
 */
function tweetbutton_field_info() {
  return array(
    'tweetbutton' => array(
      'label' => 'Tweetbutton',
      'description' => 'Creates a tweetbutton field',
      'instance_settings' => array( 'tweet_text' => '', 'author_twitter' => ''),
      'default_widget' => 'tweetbutton',
      'default_formatter' => 'tweetbutton_formatter_button_horizontal',
    ),
  );
}

/**
 * Implementation of hook_field_is_empty() 
 */
function tweetbutton_field_is_empty($item, $field) {
  return FALSE;
}

/**
 * Implementation of hook_field_instance_settings_form 
 */
function tweetbutton_field_instance_settings_form($field, $instance) {
  $settings = $instance['settings'];

  $form = array();
  
  $form['tweet_text'] = array(
    '#type' => 'textfield',
    '#title' =>  t('Tweet text'),
    '#default_value' => isset($settings['tweet_text'])? $settings['tweet_text']: variable_get('tweetbutton_tweet_text'),
  );


  $form['author_twitter'] = array(
    '#type' => 'textfield',
    '#title' => t('Author twitter account'),
    '#default_value' => isset($settings['author_twitter'])? $settings['author_twitter']: variable_get('tweetbutton_account'),
    '#description' => t('This user will be @mentioned in the suggested'),
  );
  
  if ($instance['entity_type'] == 'taxonomy_term') {
    $token_type = 'term';
  }
  else {
    $token_type = $instance['entity_type'];
  }

  $form['tokens'] = array(
    '#token_types' => array($token_type),
    '#theme' => 'token_tree',
  );
  
  return $form;
}

/**
 * Implementation of hook_field_widget_info() 
 */
function tweetbutton_field_widget_info() {
  return array(
    'tweetbutton' => array(
      'label' => t('Tweetbutton'),
      'field types' => array('tweetbutton'),
      'behaviors' => array(
        'multiple values' => FIELD_BEHAVIOR_DEFAULT,
        'default value' => FIELD_BEHAVIOR_DEFAULT
      ),
    ),
  );
}

/**
 * Implementation of hook_field_widget_form() 
 */
function tweetbutton_field_widget_form(&$form, &$form_state, $field, $instance, $langcode, $items, $delta, $element) {
  $default_author = isset($instance['settings']['author_twitter'])? $instance['settings']['author_twitter']: '';
  $default_text = isset($instance['settings']['tweet_text'])? $instance['settings']['tweet_text']: '';

  $element['account'] = array(
    '#type' => 'textfield',
    '#default_value' => !empty($items[$delta]['account'])? $items[$delta]['account']: $default_author,
    '#title' => t('Author twitter account'),
    '#description' => t('Leave blank to use global twitter account.'),
    '#maxlength' => 128,
    '#access' => user_access('use tweetbutton field'),
  );
  
  $element['text'] = array(
    '#type' => 'textfield',
    '#default_value' => !empty($items[$delta]['text'])? $items[$delta]['text']: $default_text,
    '#title' => t('Tweet text'),
    '#description' => t('Leave blank to use content title as tweet text'),
    '#maxlength' => 32,
    '#access' => user_access('use tweetbutton field'),
  );
  
  return $element;
}

/**
 * Implementation of hook_field_presave() 
 */
function tweetbutton_field_presave($entity_type, $entity, $field, $instance, $langcode, &$items) {
  if ($field['type'] == 'tweetbutton') {
    foreach ($items as $delta => $item) {
      $data = array($entity_type => $entity);
      $option = array('clear' => TRUE);
      $items[$delta]['text'] = !empty($items[$delta]['text'])? token_replace($items[$delta]['text'], $data, $option): $entity->title;
      $items[$delta]['account'] = !empty($items[$delta]['account'])? token_replace($items[$delta]['account'], $data, $option): '';
    }
  }
}


/**
 * Implementation of hook_field_formatter_info()
 */
function tweetbutton_field_formatter_info() {
  return array(
    'tweetbutton_formatter_button_vertical' => array(
      'label' => t('Tweetbutton style vertical'),
      'field types' => array('tweetbutton'),
      'settings' =>  array(
        'size' => 'medium',
      ),
    ),
    'tweetbutton_formatter_button_horizontal' => array(
      'label' => t('Tweetbutton style horizontal'),
      'field types' => array('tweetbutton'),
      'settings' =>  array(
        'size' => 'medium',
      ),
    ),
    'tweetbutton_formatter_button_none' => array(
      'label' => t('Tweetbutton style none'),
      'field types' => array('tweetbutton'),
      'settings' =>  array(
        'size' => 'medium',
      ),
    ),
  );
}

/**
 * Implements hook_field_formatter_settings_form().
 */
function tweetbutton_field_formatter_settings_form($field, $instance, $view_mode, $form, &$form_state) {
  $display = $instance['display'][$view_mode];
  $settings = $display['settings'];
  
  $element['size'] = array(
    '#type' => 'select',
    '#title' => t('Tweetbutton size'),
    '#options' => array('medium' => t('Medium'), 'large' => t('Large')),
    '#default_value' => $settings['size']
  );

  return $element;
}

/**
 * Implements hook_field_formatter_settings_summary().
 */
function tweetbutton_field_formatter_settings_summary($field, $instance, $view_mode) {
  $display = $instance['display'][$view_mode];
  $settings = $display['settings'];
  $options = array('medium' => t('Medium'), 'large' => t('Large'));
  $title = $options[$settings['size']];
  return t('Size: !title', array('!title' => $title));
}

/**
 * Implements hook_field_formatter_view().
 */
function tweetbutton_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, &$items, $display) {
  $settings = $display['settings'];

  $delta = 0;
  switch ($display['type']) {
    case 'tweetbutton_formatter_button_vertical':
      $button_type = 'vertical';
      break;
    case 'tweetbutton_formatter_button_horizontal':
      $button_type = 'horizontal';
      break;
    case 'tweetbutton_formatter_button_none':
      $button_type = 'none';
      break;
  }

  if (empty($items)) {
    $items[$delta] = array(
      'text' => '',
      'account' => ''
    );  
  }

  $uri = entity_uri($entity_type, $entity);
  $element[$delta] = array(
    '#theme' => 'tweetbutton_tweet_display',
    '#options' => array(
      'size'            => $settings['size'],
      'type'            => $button_type,
      'account'         => $items[$delta]['account'],
      'tweet_text'      => $items[$delta]['text'],
      'url'             => url($uri['path'], array('absolute' => TRUE)),
    ),
    '#entity' => $entity,
    '#entity_type' => $entity_type,
     
  );
  return $element;
}

/**
 * Implementation of hook_menu()
 */ 
function tweetbutton_menu() {
	$items = array();

  $items['admin/config/services/tweetbutton'] = array(
    'title'            => 'Tweet Button',
    'description'      => 'Configure the look and behavior of the Tweet Button appears on the site.',
    'page callback'    => 'drupal_get_form',
    'page arguments'   => array('tweetbutton_admin_settings'),
    'access arguments' => array('administer tweetbutton'),
    'file'             => 'tweetbutton.admin.inc',
    'type'             => MENU_NORMAL_ITEM,
  );

  return $items;
}

/**
 * Implementation of hook_theme()
 */
function tweetbutton_theme() {
	return array(
    'tweetbutton_tweet_display' => array(
      'variables' => array('entity' => NULL, 'entity_type' => NULL, 'options' => array()),
    ),
    'tweetbutton_follow_display' => array(
      'variables' => array('options' => array(), 'screen_name' => ''),
    ),
    'tweetbutton_hashtag_display' => array(
      'variables' => array('options' => array(), 'hashtag' => ''),
    ),
  );
}


/**
 * Implementation of hook_cron() 
 */
function tweetbutton_cron() {
  // @TODO: Fetch count of each page where tweetbutton is on and add it to column 'count' in field
  // Will be useful in sorting page based on no of tweets and add views support
  if (!variable_get('tweetbutton_get_count', FALSE)) {
    return;
  }
  
  
}

/**
 * Implementation of hook_permission()
 */
function tweetbutton_permission() {
  return array(
    'administer tweetbutton' => array(
      'title' => t('Administer Tweet Button'),
    ),
    'access tweetbutton' => array(
      'title' => t('Access Tweet Button'),
    ),
    'use tweetbutton field' => array(
      'title' => t('Use tweetbutton field to alter tweet text')
    ),
  );
}

/**
 * Implementation of hook_block_info()
 */
function tweetbutton_block_info() {
  $blocks['tweetbutton_tweet'] = array(
    'info' => t('Tweetbutton tweet'),
  );  
  $blocks['tweetbutton_follow'] = array(
    'info' => t('Tweetbutton follow'),
  );
  return $blocks;
}

/**
 * Implementation of hook_block_configure 
 */
function tweetbutton_block_view($delta = '') {
  if ($delta == 'tweetbutton_tweet') {
    $block['subject'] = t('Tweetbutton tweet');
    $block['content'] = theme('tweetbutton_tweet_display');
    return $block; 
  }
  elseif ($delta == 'tweetbutton_follow') {
    $block['subject'] = t('Tweetbutton follow');
    $block['content'] = theme('tweetbutton_follow_display');
    return $block;
  }
}

/**
 * Helper function to build the required tweet attributes
 * @param $options
 *   Context specific options
 * @return 
 *   List of attributes to be rendered for twitter tweetbutton
 */
function tweetbutton_tweet_get_attributes($options = array()) {
  global $language;
  
  $default_option = array(
    'type'        => variable_get('tweetbutton_button', 'vertical'),
    'tweet_text'  => variable_get('tweetbutton_tweet_text'),
    'language'    => variable_get('tweetbutton_language'),
    'account'     => variable_get('tweetbutton_account'),
    'rel_account' => variable_get('tweetbutton_rel_account_name'),
    'rel_desc'    => variable_get('tweetbutton_rel_account_description'),
    'size'        => variable_get('tweetbutton_size', 'medium')
  );
  
  if (empty($options['url'])) {
    $options['url'] = url($_GET['q'], array('absolute' => TRUE));  
  }
  
  if (empty($options['count_url'])) {
    $options['count_url'] = $options['url'];
  }
  
  if (module_exists('shorten') && ($service = variable_get('tweetbutton_shorten_service'))) {
    $url = shorten_url($options['url'], $service);
    // if www => http://  replacement if enabled
    if (variable_get('shorten_www', TRUE)) {
      if (strpos($url, 'www.') === 0) {
        $url = drupal_substr($url, 4);
        $url = 'http://' . $url;
      }
    }
    $options['url'] = $url;
  }
  
  
  $options += $default_option;
  
  $attributes =  array(
    'data-size'    => $options['size'],
    'data-count'   => $options['type'],
    'data-via'     => $options['account'],
    'data-related' => $options['rel_account'] . ':' . $options['rel_desc'],
    'data-text'    => $options['tweet_text'],
    'data-counturl'=> $options['count_url'],
    'data-url'     => $options['url'],
    'data-lang'    => $options['language'] == 'auto' ? $language->language : $options['language'],
    'class'        => 'twitter-share-button',
  );

  return $attributes;
}


function theme_tweetbutton_tweet_display($variables) {
  $script_url = url('http://platform.twitter.com/widgets.js', array('external' => TRUE, 'https' => TRUE));
  drupal_add_js($script_url, array('type' => 'external', 'scope' => 'footer'));
  $options = $variables['options'];
  $attributes = tweetbutton_tweet_get_attributes($options);
 
  $tweetbutton_label = isset($options['tweetbutton_label'])? $options['tweetbutton_label']: t('Tweet');
  $tweet_link = l($tweetbutton_label, 'http://twitter.com/share', array('attributes' => $attributes, 'external' => TRUE, 'https' => TRUE));
  $link = '<div class="tweetbutton-tweet tweetbutton">' . $tweet_link . '</div>';

  return $link;
}


function tweetbutton_follow_get_attributes($options) {
  global $language;
  $default_options = array(
    'show_count'       => variable_get('tweetbutton_follow_show_count', TRUE),
    'show_screen_name' => variable_get('tweetbutton_follow_screen_name'),
    'size'             => variable_get('tweetbutton_follow_size'),
    'language'         => variable_get('tweetbutton_language'),
  );
  
  $options += $default_options;
  
  $attributes = array(
    'data-show-count'       => $options['show_count'],
    'data-show-screen-name' => $options['show_screen_name'],
    'data-size'             => $options['size'],
    'data-lang'             => $options['language'] == 'auto' ? $language->language : $options['language'],
    'class'                 => 'twitter-follow-button',
  );
  return $attributes;
}

function theme_tweetbutton_follow_display($variables) {
  $script_url = url('http://platform.twitter.com/widgets.js', array('external' => TRUE, 'https' => TRUE));
  drupal_add_js($script_url, array('type' => 'external', 'scope' => 'footer'));
  
  $options = $variables['options'];
  $screen_name = $variables['screen_name'];
  if (empty($screen_name)) {
    $screen_name = variable_get('tweetbutton_follow_screen_name');
  }
  $follow_user_text = isset($options['tweetbutton_label'])? $options['tweetbutton_label']: t('Follow !screen_name', array('!screen_name' => $screen_name));
 
  $twitter_account_link = 'http://twitter.com/' . $screen_name;
  
  $attributes = tweetbutton_follow_get_attributes($options);
  
  $follow_link = l($follow_user_text, $twitter_account_link,array('attributes' => $attributes, 'external' => TRUE, 'https' => TRUE));
  $link = '<div class="tweetbutton-follow tweetbutton">' . $follow_link . '</div>';
  return $link;
}

function tweetbutton_hashtag_get_attributes($options) {
  global $language;
  $default_options = array(
    'rel_account'     => variable_get('tweetbutton_account'),
  );
  
  $options += $default_options;
  
  $attributes = array(
    'data-related' => $options['rel_account'],
    'data-lang' => $options['language'] == 'auto'? $language->language: $options['language'],
    'class' => 'twitter-hashtag-button',
  );
}

function theme_tweetbutton_hashtag_display($variables) {
  $script_url = url('http://platform.twitter.com/widgets.js', array('external' => TRUE));
  drupal_add_js($script_url, array('type' => 'external', 'scope' => 'footer'));
  
  $options = $variables['options'];
  $attributes = tweetbutton_hashtag_get_attributes($options);
  $query = array();
  if (!empty($options['tweet_text'])) {
    $query['tweet_text'] = $options['tweet_text'];
  }
  
  if (!empty($variables['hashtag'])) {
    $query['button_hashtag'] = $variables['hashtag'];
  }
  
  $hash_link = l($hash_text, 'http://twitter.com/intent/tweet', array('query' => $query, 'attributes' => $attributes, 'external' => TRUE, 'https' => TRUE));
  return '<div class="tweetbutton-hashtag tweetbutton">' . $hash_link . '</div>';
}