<?php

define('VIDEO_CCK_OOYALA_MAIN_URL', 'http://www.ooyala.com/');
define('VIDEO_CCK_OOYALA_PLAYER_API_INFO', 'http://www.ooyala.com/api/OoyalaPlayerAPI.pdf');
define('VIDEO_CCK_OOYALA_PARTNER_API_INFO', 'http://www.ooyala.com/api/OoyalaPartnerAPI.pdf');
define('VIDEO_CCK_OOYALA_REST_ENDPOINT', 'http://www.ooyala.com/partner/');

/**
 * hook video_cck_PROVIDER_info
 * this returns information relevant to a specific 3rd party video provider
 * @return
 *   an array of strings requested by various admin and other forms
 *   'name' => the translated name of the provider
 *   'url' => the url to the main page for the provider
 *   'settings_description' => a description of the provider that will be posted in the admin settings form
 *   'supported_features' => an array of rows describing the state of certain supported features by the provider.
 *      These will be rendered in a table, with the columns being 'Feature', 'Supported', 'Notes'.
 */
function video_cck_ooyala_info() {
  $name = t('Ooyala');
  $features = array(
    array(t('Autoplay'), t('Yes'), ''),
    array(t('Thumbnails'), t('Yes'), t('')),
  );
  return array(
    'provider' => 'ooyala',
    'name' => $name,
    'url' => VIDEO_CCK_OOYALA_MAIN_URL,
    'settings_description' => t('These settings specifically affect videos displayed from !ooyala. Learn more about its !player_api and its !partner_api.', array('!ooyala' => l($name, VIDEO_CCK_OOYALA_MAIN_URL, array('target' => '_blank')), '!player_api' => l(t('Player API'), VIDEO_CCK_OOYALA_PLAYER_API_INFO, array('target' => '_blank')), '!partner_api' => l(t('Partner API'), VIDEO_CCK_OOYALA_PARTNER_API_INFO, array('target' => '_blank')))),
    'supported_features' => $features,
  );
}

/**
 * hook video_cck_PROVIDER_settings
 * this should return a subform to be added to the video_cck_settings() admin settings page.
 * note that a form field will already be provided, at $form['PROVIDER'] (such as $form['ooyala'])
 * so if you want specific provider settings within that field, you can add the elements to that form field.
 */
function video_cck_ooyala_settings() {
  $form['ooyala']['api'] = array(
    '#type' => 'fieldset',
    '#title' => t('Ooyala API'),
    '#description' => t('If you wish to display thumbnails, you will need to use your backlot API information. You will need to create an account at from the !ooyala. Note that you do not need this key to display Ooyala videos.', array('!ooyala' => l('Ooyala website', VIDEO_CCK_OOYALA_API_MAIN_URL, array('target' => '_blank')))),
    '#collapsible' => true,
    '#collapsed' => true,
  );
  $form['ooyala']['api']['video_cck_ooyala_partner_code'] = array(
    '#type' => 'textfield',
    '#title' => t('Ooyala Partner Code'),
    '#default_value' => variable_get('video_cck_ooyala_partner_code', ''),
    '#description' => t('Please enter your Ooyala Partner Code here.'),
  );
  $form['ooyala']['api']['video_cck_ooyala_secret_code'] = array(
    '#type' => 'textfield',
    '#title' => t('Ooyala Secret Code'),
    '#default_value' => variable_get('video_cck_ooyala_secret_code', ''),
    '#description' => t('Please enter your Ooyala Secret Code here.'),
  );
  return $form;
}

function video_cck_ooyala_query($params) {
    return video_cck_ooyala_request('query', $params);
}

function video_cck_ooyala_query_thumbnails($params) {
    return video_cck_ooyala_request('thumbnails', $params);
}

/**
 * this is a wrapper for video_cck_request_xml that includes ooyala's codes
 */
function video_cck_ooyala_request($request_type, $args = array(), $cached = TRUE) {
  // set expiry time if not already there
  if (!array_key_exists('expires', $args)) {
    $args['expires'] = time() + 900;
  }

  // begin signature by grabbing secret code
  $string_to_sign = trim(variable_get('video_cck_ooyala_secret_code', ''));

  // add sorted parameters to the string
  ksort($args);
  foreach ($args as $key => $value) {
    $string_to_sign .= $key . '=' . $value;
  }

  // digest and encode the string, and add it to the parameters
  $digest = hash('sha256', $string_to_sign, true);
  $args['signature'] = ereg_replace('=+$', '', trim(base64_encode($digest)));

  // set partner code
  $args['pcode'] = trim(variable_get('video_cck_ooyala_partner_code', ''));

  // finally, return the request
  $request = module_invoke('emfield', 'request_xml', 'ooyala', VIDEO_CCK_OOYALA_REST_ENDPOINT . $request_type, $args, $cached);
  return $request;
}

/**
 * hook video_cck_PROVIDER_extract
 * this is called to extract the video code from a pasted URL or embed code.
 * @param $embed
 *   an optional string with the pasted URL or embed code
 * @return
 *   either an array of regex expressions to be tested, or a string with the video code to be used
 *   if the hook tests the code itself, it should return either the string of the video code (if matched), or an empty array.
 *   otherwise, the calling function will handle testing the embed code against each regex string in the returned array.
 */
function video_cck_ooyala_extract($embed = '') {
  // src="http://www.ooyala.com/v/nvbQQnvxXDk"
  // http://ooyala.com/watch?v=nvbQQnvxXDk
  // http://www.ooyala.com/watch?v=YzFCA-xUc8w&feature=dir
  return array(
    '@embedCode=(\w+)" /><embed src="http://www.ooyala.com/@',
  );
}

/**
 * hook video_cck_PROVIDER_embedded_link($video_code)
 * returns a link to view the video at the provider's site
 *  @param $video_code
 *    the string containing the video to watch
 *  @return
 *    a string containing the URL to view the video at the original provider's site
 */
function video_cck_ooyala_embedded_link($video_code) {
  return false;
}

/**
 * the embedded flash displaying the ooyala video
 */
function theme_video_cck_ooyala_flash($embed, $width, $height, $autoplay) {
  if ($embed) {
    if ($autoplay) {
      $autoplay_value = '&amp;autoplay=1';
    }
    $output .= "    <object type=\"application/x-shockwave-flash\" height=\"$height\" width=\"$width\" data=\"http://www.ooyala.com/player.swf\" id=\"ooyalaPlayer\" >
      <param name=\"movie\" value=\"http://www.ooyala.com/player.swf\" />
      <param name=\"quality\" value=\"best\"/>
      <param name=\"bgcolor\" value=\"#000000\"/>
      <param name=\"allowScriptAcess\" value=\"always\"/>
      <param name=\"allowFullScreen\" value=\"true\"/>
      <param name=\"FlashVars\" value=\"embedCode=$embed$autoplay_value\" />
      <param name=\"wmode\" value=\"transparent\" />
    </object>\n";
  }
  return $output;
}

/**
 * hook video_cck_PROVIDER_thumbnail
 * returns the external url for a thumbnail of a specific video
 * TODO: make the args: ($embed, $field, $item), with $field/$item provided if we need it, but otherwise simplifying things
 *  @param $field
 *    the field of the requesting node
 *  @param $item
 *    the actual content of the field from the requesting node
 *  @return
 *    a URL pointing to the thumbnail
 */
function video_cck_ooyala_thumbnail($field, $item, $formatter, $node, $width, $height) {
  // oolaya requires a width and height, so set some defaults
  $width = $width ? $width : '120';
  $height = $height ? $height : '90';
  $args['range'] = '0-4';
  $args['resolution'] = $width . 'x' . $height;
  $args['embedCode'] = $item['value'];
  $request = video_cck_ooyala_query_thumbnails($args);

  // get the thumbnail URLs out of the returned XML document
  $thumbnails = array_pop($request);
  $thumbnails = $thumbnails['THUMBNAIL'];
  $urls = array();
  for ($i = 0; $i < count($thumbnails); $i += 2)
    $urls[] = $thumbnails[$i];

  // choose one randomly
  $rand = rand(0, 4);
  $tn = $urls[$rand];
  return $tn;
}

/**
 * hook video_cck_PROVIDER_video
 * this actually displays the full/normal-sized video we want, usually on the default page view
 *  @param $embed
 *    the video code for the video to embed
 *  @param $width
 *    the width to display the video
 *  @param $height
 *    the height to display the video
 *  @param $field
 *    the field info from the requesting node
 *  @param $item
 *    the actual content from the field
 *  @return
 *    the html of the embedded video
 */
function video_cck_ooyala_video($embed, $width, $height, $field, $item, $autoplay) {
  $output = theme('video_cck_ooyala_flash', $embed, $width, $height, $autoplay);
  return $output;
}

/**
 * hook video_cck_PROVIDER_video
 * this actually displays the preview-sized video we want, commonly for the teaser
 *  @param $embed
 *    the video code for the video to embed
 *  @param $width
 *    the width to display the video
 *  @param $height
 *    the height to display the video
 *  @param $field
 *    the field info from the requesting node
 *  @param $item
 *    the actual content from the field
 *  @return
 *    the html of the embedded video
 */
function video_cck_ooyala_preview($embed, $width, $height, $field, $item, $autoplay) {
  $output = theme('video_cck_ooyala_flash', $embed, $width, $height, $autoplay);
  return $output;
}
