<?php

// Guide:
// http://www.metaltoad.com/blog/drupal-7-tutorial-creating-custom-formatters

/**
 * Implements hook_field_formatter_info().
 */
function groups_social_link_field_formatter_info() {
  return array(
    'groups_social_link_formatter' => array(
      'label' => t('Social Link'),
      'field types' => array('link_field'),
      'settings'  => array(
        'provider' => 'twitter',
      ),
    ),
  );
}

/**
 * Implements hook_field_formatter_settings_form().
 */
function groups_social_link_field_formatter_settings_form($field, $instance,
  $view_mode, $form, &$form_state) {
  $element = array();
  $element['provider'] = array(
    '#type'           => 'select',
    '#title'          => t('Provider'),
    '#description'    => t('Select social provider'),
    '#default_value'  => $settings['provider'],
    '#options'        => array(
      'twitter'       => 'Twitter',
      'weibo'         => 'Weibo',
      'facebook'      => 'Facebook',
    ),
  );
  return $element;
}

/**
 * Implements hook_field_formatter_settings_summary().
 */
function groups_social_link_field_formatter_settings_summary($field, $instance,
  $view_mode) {
  $display = $instance['display'][$view_mode];
  $settings = $display['settings'];
  $summary = t('Use a @provider provider to display link.', array(
    '@provider'     => $settings['provider'],
  ));
  return $summary;
}

/**
 * Implements hook_field_formatter_view().
 */
function groups_social_link_field_formatter_view($entity_type, $entity, $field,
  $instance, $langcode, $items, $display) {
  $settings = $display['settings'];
  $element = array();
  foreach ($items as $delta => $item) {
    // dpm($item, 'item');
    $url = $item['url']; // Getting the actual value
  }
  if (!empty($url)) {
    $display_value = '';
    switch ($settings['provider']) {
      case 'twitter':
        $glyphicon = 'fa-twitter';
        $display_value = '@'.basename($url);
        break;
      case 'weibo':
        $glyphicon = 'fa-weibo';
        $display_value = '@'.basename($url);
        break;
    }
    $element[0]['#markup'] = format_string(
      '<div class="social-link social-link-@provider">'.
      '<i class="fa @glyphicon" aria-hidden="true"></i>'.
      '<a href="@url">@display_value</a>'.
      '</div>',
      array(
        '@glyphicon' => $glyphicon,
        '@provider' => $settings['provider'],
        '@url' => $url,
        '@display_value' => $display_value,
      ));
  }
  return $element;
}