<?php


/**
 * Implements hook_field_formatter_info().
 */
function custom_maps_field_formatter_info() {
  return array(
    'speed' => array( 
      'label' => t('Speed'),
      'field types' => array('number_float'),
    ),
    'distance' => array( 
      'label' => t('Distance'),
      'field types' => array('number_float'), 
    ),
    'duration' => array( 
      'label' => t('Duration'),
      'field types' => array('number_float'), 
    ),
    'meters' => array( 
      'label' => t('Distance (Meters)'),
      'field types' => array('number_float'), 
    ),
    'pace' => array( 
      'label' => t('Pace'),
      'field types' => array('number_float'), 
    ),
  );
}


/**
 * Implements hook_field_formatter_view().
 */
function custom_maps_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
  $element = array(); // Initialize the var
  $settings = $display['settings']; // get the settings
  // $size = $settings['pic_size']; // The Size setting selected in the settings form
  // $tooltip = $settings['tooltip']; // The tool tip assigned in settings
  
  switch ($display['type']) {
    case 'speed':
      $element[0]['#markup'] = @__number_format($items[0]['value'], 2 ) . ' Km/h';
      break;
    case 'distance':
      $element[0]['#markup'] = @__number_format($items[0]['value'] / 1000, 2 ) . ' Km';
      break;
    case 'duration':
      // $element[0]['#markup'] = format_interval($items[0]['value'] , 3 );
      $element[0]['#markup'] = __format_seconds($items[0]['value']);
      break;
    case 'meters':
      $element[0]['#markup'] = intval($items[0]['value']) . ' m';
      break;
    case 'pace':
      $element[0]['#markup'] = @str_replace('00h:', '', gmdate('H\h:i\m:s\s', $items[0]['value'] ) . ' min/km');
      break;

  }


  return $element;
}

function __format_seconds($seconds) {
  return @str_replace('00h:', '', gmdate('H\h:i\m:s\s', $seconds ));
}
function __number_format($number, $precision = 2, $separator = '.')
{
    $numberParts = explode($separator, $number);
    $response = $numberParts[0];
    if(count($numberParts)>1){
        $response .= $separator;
        $response .= substr($numberParts[1], 0, $precision);
    }
    return $response;
}