<?php

/**
 * Implements hook_theme().
 */
function video_embed_field_overlay_theme() {
  return array(
    'video_embed_field_overlay' => array(
      'variables' => array(
        'show_thumbnail' => TRUE,
        'thumbnail_path' => NULL,
        'description' => NULL,
        'image_style' => NULL,
        'video_url' => NULL,
        'video_style' => 'normal',
      ),
    ),
  );
}

/**
 * Implements hook_field_formatter_info().
 */
function video_embed_field_overlay_field_formatter_info() {
  return array(
    'video_embed_field_overlay' => array(
      'label' => t('Overlay'),
      'field types' => array('video_embed_field'),
      'settings' => array(
        'show_thumbnail' => TRUE,
        'video_style' => 'normal',
        'image_style' => image_style_load('video_thumbnail') ? 'video_thumbnail' : 'none',
        'description' => 1,
        'overlay' => 'dom-window'),
    ),
  );
}

/**
 * Implements hook_field_formatter_settings_form().
 */
function video_embed_field_overlay_field_formatter_settings_form($field, $instance, $view_mode, $form, &$form_state) {
  $display = $instance['display'][$view_mode];
  $settings = $display['settings'];
  $element = array();

  if ($display['type'] == 'video_embed_field_overlay') {
    // Video style
    $video_styles = video_embed_field_video_style_options(FALSE);
    $element['video_style'] = array(
      '#title' => t('Video style'),
      '#type' => 'select',
      '#default_value' => $settings['video_style'],
      '#options' => $video_styles,
    );
    // Show an image?
    $element['show_thumbnail'] = array(
      '#title' => t('Show thumbnail'),
      '#type' => 'select',
      '#options' => array(1 => t('Yes'), 0 => t('No')),
      '#default_value' => $settings['show_thumbnail'],
    );
    // Image style
    $element['image_style'] = array(
      '#title' => t('Image style'),
      '#type' => 'select',
      '#options' => image_style_options(FALSE),
      '#default_value' => $settings['image_style'],
      '#empty_option' => t('None (original image)'),
    );

    // Overlay library
    $element['overlay'] = array(
      '#title' => t('Overlay Library:'),
      '#type' => 'select',
      '#options' => array('dom-window' => t('DOM Window')),
      '#default_value' => $settings['overlay'],
    );
  }

  return $element;
}

/**
 * Implements hook_field_formatter_settings_summary().
 */
function video_embed_field_overlay_field_formatter_settings_summary($field, $instance, $view_mode) {
  $display = $instance['display'][$view_mode];
  $settings = $display['settings'];

  $summary = array();

  if ($display['type'] == 'video_embed_field_overlay') {
    // Video style
    $video_styles = video_embed_field_video_style_options(FALSE);
    // Styles could be lost because of enabled/disabled modules that defines
    // their styles in code.
    if (isset($video_styles[$settings['video_style']])) {
      $summary[] = t('Video style: @style', array('@style' => $video_styles[$settings['video_style']]));
    }

    // Display thumbnail?
    if (isset($settings['show_thumbnail']) && $settings['show_thumbnail'] == TRUE) {
      $summary[] = t('Link: Showing thumbnail in link.');
    }
    else {
      $summary[] = t('Link: Showing plain-text link.');
    }

    // Image style
    $image_styles = image_style_options(FALSE);
    if (isset($image_styles[$settings['image_style']])) {
      $summary[] = t('Image style: @style', array('@style' => $image_styles[$settings['image_style']]));
    } //No Image style (original image)
    else {
      $summary[] = t('Original Image.');
    }

    // Overlay
    // @TODO: extend this to use a list of available overlay libraries.
    if (isset($settings['overlay'])) {
      $summary[] = t('Overlay Library: @overlay.', array('@overlay' => 'DOM Window'));
    }
    else {
      $summary[] = t('Overlay Library: @overlay.', array('@overlay' => 'DOM Window'));
    }
  }

  return implode('<br />', $summary);
}

/**
 * Implements hook_field_formatter_view().
 */
function video_embed_field_overlay_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
  $element = array();

  foreach ($items as $delta => $item) {
    if ($display['type'] == 'video_embed_field_overlay') {
      if (!isset($item['description']) || empty($item['description'])) {
        $item['description'] = t('Play video');
      }
      $element[$delta] = array(
        '#theme' => 'video_embed_field_overlay',
        '#thumbnail_path' => $item['thumbnail_path'],
        '#image_style' => $display['settings']['image_style'],
        '#video_url' => $item['video_url'],
        '#description' => $item['description'],
        '#show_thumbnail' => $display['settings']['show_thumbnail'],
        '#video_style' => $display['settings']['video_style'],
        '#attached' => array(
          'css' => array(
            drupal_get_path('module', 'video_embed_field_overlay') . '/css/video_embed_field_overlay.css',
          ),
        ),
      );
      if (video_embed_field_overlay_library_exists()) {
        $element[$delta]['#attached']['library'] = array(array('domwindow', 'domwindow'));
        $element[$delta]['#attached']['js'] = array(drupal_get_path('module', 'video_embed_field_overlay') . '/js/video_embed_field_overlay.js');
        drupal_add_js(array(
          'video_embed_field_overlay' => array(
            'path' => drupal_get_path('module', 'video_embed_field_overlay'),
          ),
          ), 'setting');
      }
      else {
        drupal_set_message(t('DOM Window library was not found.'), 'warning');
      }
    }
  }

  return $element;
}

/**
 * Theme function wraps a video_embed_field element in an overlay
 */
function theme_video_embed_field_overlay(&$variables) {
  $output = '';

  if (isset($variables['show_thumbnail']) && $variables['show_thumbnail'] == TRUE) {
    if (isset($variables['image_style']) && $variables['image_style']) {
      $thumbnail = theme('image_style', array(
        'path' => $variables['thumbnail_path'],
        'style_name' => $variables['image_style']));
    }
    else {
      $thumbnail = theme('image', array(
        'path' => $variables['thumbnail_path'],
        'alt' => $variables['description'],
        ));
    }
  }

  if (!isset($thumbnail) || empty($thumbnail)) {
    $link = l($variables['description'], $variables['video_url'], array(
      'attributes' => array(
        'class' => array('overlay'),
        'title' => $variables['description'],
      ),
      'html' => TRUE,
      ));
  }
  else {
    $link = l($thumbnail, $variables['video_url'], array(
      'attributes' => array(
        'class' => array('overlay'),
      ),
      'html' => TRUE,
      ));
  }

  if (!isset($variables['video_style']) || empty($variables['video_style'])) {
    $variables['video_style'] = 'normal';
  }

  $embed_code = theme('video_embed_field_embed_code', array(
    'url' => $variables['video_url'],
    'style' => $variables['video_style'],
    ));

  $output .= '<div class="video-overlay">';
  $output .= '  <div class="video-overlay-thumbnail">';
  $output .= '    ' . $link;
  $output .= '  </div>';
  $output .= '  <div class="video-overlay-source">';
  $output .= '    ' . $embed_code;
  $output .= '  </div>';
  $output .= '</div>';
  return $output;
}

/**
 * Implements hook_image_default_styles().
 */
function video_embed_field_overlay_image_default_styles() {
  $styles = array();

  // Exported image style: video_thumbnail
  $styles['video_thumbnail'] = array(
    'name' => 'video_thumbnail',
    'effects' => array(
      1 => array(
        'label' => 'Scale and crop',
        'help' => 'Scale and crop will maintain the aspect-ratio of the original image, then crop the larger dimension. This is most useful for creating perfectly square thumbnails without stretching the image.',
        'effect callback' => 'image_scale_and_crop_effect',
        'dimensions callback' => 'image_resize_dimensions',
        'form callback' => 'image_resize_form',
        'summary theme' => 'image_resize_summary',
        'module' => 'image',
        'name' => 'image_scale_and_crop',
        'data' => array(
          'width' => '510',
          'height' => '290',
        ),
        'weight' => '1',
      ),
    ),
  );

  // If the user has enabled the imagecache_canvasactions module, use it.
  // @see http://drupal.org/project/imagecache_actions
  if (module_exists('imagecache_canvasactions')) {
    $styles['video_thumbnail']['effects'][] = array(
      'label' => 'Overlay (watermark)',
      'help' => 'Choose the file image you wish to use as an overlay, and position it in a layer on top of the canvas.',
      'effect callback' => 'canvasactions_file2canvas_image',
      'form callback' => 'canvasactions_file2canvas_form',
      'summary theme' => 'canvasactions_file2canvas_summary',
      'module' => 'imagecache_canvasactions',
      'name' => 'canvasactions_file2canvas',
      'data' => array(
        'xpos' => 'center',
        'ypos' => 'center',
        'alpha' => '100',
        // 'path' => drupal_get_path('module', 'video_embed_field_overlay') . '/images/video_overlay.png',
        'path' => 'module://video_embed_field_overlay/images/video_overlay.png',
      ),
      'weight' => '2',
    );
  }

  return $styles;
}

/**
 * Implements hook_modules_enabled().
 */
function video_embed_field_overlay_modules_enabled($modules) {
  if (in_array('imagecache_canvasactions', $modules)) {
    drupal_static_reset('image_effect_definitions');
    $style = image_style_load('video_thumbnail');
    if ($style) {
      image_default_style_revert($style);
      drupal_set_message(t('Video Thumbnail image style has been reverted to its original state and the overlay action has been added.'));
      image_flush_caches();
    }
  }
}

/**
 * Helper function that checks if the domwindow library is present.
 */
function video_embed_field_overlay_library_exists() {
  $libraries = array();
  if (empty($libraries)) {
    $libraries = libraries_get_libraries();
  }
  return array_key_exists('jquery.domwindow', $libraries);
}
