<?php

/**
 * @file
 *
 */

function media_token_info() {
  
  $info['types']['file_field'] = array(
    'name' => t('Media'),
    'description' => t('Tokens related to a media field.'),
    'hidden' => TRUE,
  );
  
  $default_text = ' ' . t('Defaults to first value.');
  
  $info['tokens']['file_field'] = array(
    'field' => array(
      'name' => t('Field token value'),
      'description' => t('Default: The value returned by the token field formatter.') . $default_text,
    ),
    'url' => array(
      'name' => t('URL'),
      'description' => t('URL of the media resource.') . $default_text,
      'type' => 'array',
    ),
    'filename' => array(
      'name' => t('Filename'),
      'description' => t('Filenamef the media resource.') . $default_text,
      'type' => 'array',
    ),
    'filemime' => array(
      'name' => t('Mime type'),
      'description' => t('Mime type of the media resource.') . $default_text,
      'type' => 'array',
    ),
    'type' => array(
      'name' => t('File type'),
      'description' => t('File type of the media resource.') . $default_text,
      'type' => 'array',
    ),
    'image' => array(
      'name' => t('Image'),
      'description' => t('URL of a representative image for the media resource, e.g. a video thumbnail.') . $default_text,
      'type' => 'array',
    ),
    'height' => array(
      'name' => t('Height'),
      'description' => t('Height of the media resource, for videos or images.') . $default_text,
      'type' => 'array',
    ),
    'width' => array(
      'name' => t('Width'),
      'description' => t('Width of the media resource, for videos or images.') . $default_text,
      'type' => 'array',
    ),
    'https-url' => array(
      'name' => t('Secure URL'),
      'description' => t('URL of the media resource using https.') . $default_text,
      'type' => 'array',
    ),
    'https-image' => array(
      'name' => t('Secure image'),
      'description' => t('URL of a representative image for the media resource using https, usually for videos.') . $default_text,
      'type' => 'array',
    ),
    // I don't know how to get these reliably.
    //    'stream-url' => array(
    //      'name' => t('Stream URL'),
    //      'description' => t('URL of an MP4 or AAC stream.') . $default_text,
    //      'type' => 'array',
    //    ),
    //    'stream-type' => array(
    //      'name' => t('Stream type'),
    //      'description' => t('The mime type of the MP4 or AAC stream.') . $default_text,
    //      'type' => 'array',
    //    ),
  );
  
  
  $all_fields = field_info_field_map();
  foreach ($all_fields as $field_name => $field) {
    if ($field['type'] == 'file') {
      $field_info = _token_field_info($field_name);
      foreach (array_keys($field['bundles']) as $entity_type) {
        $info['tokens'][$entity_type][$field_name] = array(
          'name' => $field_info['label'],
          'description' => $field_info['description'],
          'type' => 'file_field',
          'module' => 'media',
        );
      }
    }
  }
  
  return $info;
}

function media_tokens($type, $tokens, $data = array(), $options = array()) {
  $replacements = array();
  
  // Check that this token call contains the data we need
  if ($type == 'entity' && !empty($data['entity_type']) && !empty($data['entity']) && !empty($data['token_type'])) {
    
    foreach ($tokens as $name => $original) {
      
      // split out the token into its parts
      list($field_name, $property, $array_handler) = explode(':', $name, 2);
      
      // check that the field has content and that we should handle it
      if (!empty($data['entity']->$field_name) && _token_module($data['token_type'], $field_name) == 'media') {
        
        // get basic information
        $entity_type = $data['entity_type'];
        $langcode = isset($options['language']) ? $options['language']->language : NULL;
        $entity = clone $data['entity'];
        
        // if it is the field we want, let field module handle it
        if (empty($property) || $property == 'field') {
          unset($entity->_field_view_prepared);
          $field_output = field_view_field($entity_type, $entity, $field_name, 'token', $langcode);
          $field_output['#token_options'] = $options;
          $field_output['#prerender'][] = 'token_pre_render_field_token';
          $replacements[$original] = drupal_render($field_output);
        }
        
        // if we want a single property, get it
        else {
          $display_language = field_language($entity_type, $entity, $field_name, $langcode);
          $values = _media_tokens_get_property($entity->{$field_name}[$display_language], $property, $array_handler);
          
          // we may get a single value or an array - handle array with the array function from token module
          $replacements[$original] = is_array($values) ?
              token_generate('array', token_find_with_prefix($tokens, "$field_name:$property", array('array' => $values), $options)) :
              $values;
        }
        unset($entity);
      }
    }
  }
  return $replacements;
}

function _media_tokens_get_property($files, $property, $array_handler = 'first') {
  
  // If we only need the first varible,
  $return_only_one = ($array_handler == 'first' || empty($array_handler) || $array_handler == 'value:0');
  $info = &drupal_static(__FUNCTION__); // This static variable stores image info
  foreach ($files as $file) {
    $file['url'] = file_create_url($file['uri']);
    $file['https-url'] = str_replace('http://', 'https://', $file['url']);
    
    // filename, filemime, type, url, https-url
    if (isset($file[$property])) {
      $value = $file[$property];
    }
    
    // image, height, width, https-image
    elseif (!empty($info[$file['fid']])) { // info exists in static variable
      $value = $info[$file['fid']][$property] ?: NULL;
    }
    
    else { // get info from image file
      if ($file['type'] == 'image') { // for image files
        $imageuri = $file['uri'];
      }
      elseif ($file['type'] == 'video') { // for video files
        list($provider, $filename) = explode('://v/', $file['uri']);
        $imageuri = "public://media-$provider/$filename.jpg";
      }
      else { // don't know what to do for other types
        $imageuri = FALSE;
      }
      
      if ($info[$file['fid']] = image_get_info($imageuri)) {
        $info[$file['fid']]['image'] = file_create_url($imageuri);
        $info[$file['fid']]['https-image'] = str_replace('http://', 'https://', $info[$file['fid']]['image']);
      }
      
      $value = $info[$file['fid']][$property] ?: NULL;
    }
    
    if ($return_only_one) {
      return $value;
    }
    $values[] = $value;
  }
  
  return $values;
}
