<?php

/**
 * @file
 * Install, update and uninstall functions for the video_embed_field module.
 */

/**
 * Install file for video_embed_field module
 * @author jcaldwell
 */

/**
 * Implements hook_field_schema().
 */
function video_embed_field_field_schema($field) {
  switch ($field['type']) {
    case 'video_embed_field':
      $columns = array(
        'video_url' => array(
          'type' => 'varchar',
          'length' => 512,
          'default' => '',
        ),
        'thumbnail_path' => array(
          'type' => 'varchar',
          'length' => 512,
          'default' => '',
        ),
        'video_data' => array(
          'type' => 'blob',
          'not null' => FALSE,
          'size' => 'big',
          'serialize' => TRUE,
        ),
        'embed_code' => array(
          'type' => 'varchar',
          'length' => 1024,
          'default' => '',
        ),
        'description' => array(
          'type' => 'text',
          'not null' => FALSE,
        ),
      );
      $indexes = array();
      break;
  }

  return array(
    'columns' => $columns,
    'indexes' => $indexes,
  );
}

/**
 * Implements hook_schema().
 */
function video_embed_field_schema() {
  $schema['vef_video_styles'] = array(
    'description' => 'Stores video embed styles.',
    'export' => array(
      'key' => 'name',
      'identifier' => 'video_embed_style',
      'default hook' => 'default_video_embed_styles',
      'api' => array(
        'owner' => 'video_embed_field',
        'api' => 'default_video_embed_styles',
        'minimum_version' => 1,
        'current_version' => 1,
      ),
    ),
    'fields' => array(
      'name' => array(
        'description' => 'The machine-readable option set name.',
        'type' => 'varchar',
        'length' => 255,
        'not null' => TRUE,
      ),
      'title' => array(
        'description' => 'The human-readable title for this option set.',
        'type' => 'varchar',
        'length' => 255,
        'not null' => TRUE,
      ),
      'data' => array(
        'description' => 'The configuration data for the style.',
        'type' => 'blob',
        'size' => 'big',
        'not null' => TRUE,
        'serialize' => TRUE,
      ),
    ),
    'primary key' => array('name'),
  );
  return $schema;
}

/**
 * Implements hook_uninstall().
 */
function video_embed_field_uninstall() {
  variable_del('video_embed_field_youtube_api_key');
}

/**
 * Adds an optional description form.
 */
function video_embed_field_update_7000() {
  // Get the list of fields of type 'video_embed_field'.
  $video_embed_fields = array();
  foreach (field_info_fields() as $field_name => $field_info) {
    if ($field_info['type'] == 'video_embed_field') {
      $video_embed_fields[$field_name] = field_read_field($field_name);
    }
  }

  foreach ($video_embed_fields as $field) {
    if ($field['deleted']) {
      $table = "field_deleted_data_{$field['id']}";
      $revision_table = "field_deleted_revision_{$field['id']}";
    }
    else {
      $table = "field_data_{$field['field_name']}";
      $revision_table = "field_revision_{$field['field_name']}";
    }
    $column = $field['field_name'] . '_description';
    db_add_field($table, $column, array('type' => 'text', 'not null' => FALSE));
    db_add_field($revision_table, $column, array('type' => 'text', 'not null' => FALSE));
  }

  return t('Additional columns added.');
}

/**
 * Adds video style storage table.
 */
function video_embed_field_update_7001() {
  if (!db_table_exists('vef_video_styles')) {
    $schema = video_embed_field_schema();
    db_create_table('vef_video_styles', $schema['vef_video_styles']);
  }

  return t('Video styles storage table created.');
}
/**
 * Adds field for storing the path to the video thumbnail.
 */
function video_embed_field_update_7002() {
  // Get the list of fields of type 'video_embed_field'.
  $video_embed_fields = array();
  foreach (field_info_fields() as $field_name => $field_info) {
    if ($field_info['type'] == 'video_embed_field') {
      $video_embed_fields[$field_name] = field_read_field($field_name);
    }
  }

  foreach ($video_embed_fields as $field) {
    if ($field['deleted']) {
      $table = "field_deleted_data_{$field['id']}";
      $revision_table = "field_deleted_revision_{$field['id']}";
    }
    else {
      $table = "field_data_{$field['field_name']}";
      $revision_table = "field_revision_{$field['field_name']}";
    }
    $column = $field['field_name'] . '_thumbnail_path';
    db_add_field($table, $column, array(
      'type' => 'varchar',
      'length' => 512,
      'default' => '',
    ));
    db_add_field($revision_table, $column, array(
      'type' => 'varchar',
      'length' => 512,
      'default' => '',
    ));
  }

  return t('Thumbnail column added.');
}

/**
 * Enables inline colorbox support if colorbox is installed.
 *
 * [NO LONGER NEEDED - This update hook does nothing]
 */
function video_embed_field_update_7003() {
}

/**
 * Enables colorbox load support if colorbox is installed.
 */
function video_embed_field_update_7004() {
  variable_set('colorbox_load', 1);
}

/**
 * Adds data column to field database.
 */
function video_embed_field_update_7005() {
  // Get the list of fields of type 'video_embed_field'.
  $video_embed_fields = array();
  foreach (field_info_fields() as $field_name => $field_info) {
    if ($field_info['type'] == 'video_embed_field') {
      $video_embed_fields[$field_name] = field_read_field($field_name);
    }
  }

  foreach ($video_embed_fields as $field) {
    if ($field['deleted']) {
      $table = "field_deleted_data_{$field['id']}";
      $revision_table = "field_deleted_revision_{$field['id']}";
    }
    else {
      $table = "field_data_{$field['field_name']}";
      $revision_table = "field_revision_{$field['field_name']}";
    }
    $column = $field['field_name'] . '_video_data';
    db_add_field($table, $column, array(
      'type' => 'blob',
      'not null' => FALSE,
      'size' => 'big',
      'serialize' => TRUE,
    ));
    db_add_field($revision_table, $column, array(
      'type' => 'blob',
      'not null' => FALSE,
      'size' => 'big',
      'serialize' => TRUE,
    ));
  }

  return t('Data column added. Please clear cache.');
}

/**
 * Updates vef_video_styles table structure.
 */
function video_embed_field_update_7006() {
  // Convert the table structure.
  db_drop_field('vef_video_styles', 'vsid');
  db_add_primary_key('vef_video_styles', array('name'));
  db_drop_unique_key('vef_video_styles', 'name');

  db_add_field('vef_video_styles', 'title', array(
    'type' => 'varchar',
    'length' => 255,
    'not null' => TRUE,
    'default' => '',
  ));
  // Update title and name values.
  $result = db_select('vef_video_styles', 'vef')
    ->fields('vef', array('name'))
    ->execute();
  foreach ($result as $record) {
    // Set current name as title.
    db_update('vef_video_styles')
      ->fields(array(
        'title' => $record->name,
      ))
      ->condition('name', $record->name)
      ->execute();

    // Update name to fit with machine_name constraints.
    $new_name = preg_replace('/[^a-z0-9_]+/', '_', drupal_strtolower($record->name));
    if ($new_name != $record->name) {
      // Check if new name already exists in the database.
      $counter = 1;
      $base_name = $new_name;
      while (TRUE) {
        $result = db_select('vef_video_styles', 'vef')
          ->fields('vef', array('name'))
          ->condition('name', $new_name)
          ->execute();
        if ($result->rowCount()) {
          $new_name = $base_name . '_' . $counter;
        }
        else {
          db_update('vef_video_styles')
            ->fields(array(
              'name' => $new_name,
            ))
            ->condition('name', $record->name)
            ->execute();
          break;
        }
      }
    }
  }

  return t('Database schema updated successfully');
}

/**
 * Update youtube "hd" URL deprecated parameter.
 */
function video_embed_field_update_7007() {
  drupal_get_schema('vef_video_styles', TRUE);
  ctools_include('export');
  $styles = ctools_export_load_object('vef_video_styles');
  foreach ($styles as $style) {
    if (isset($style->data['youtube']['hd'])) {
      if ($style->data['youtube']['hd']) {
        $style->data['youtube']['vq'] = 'hd720';
      }
      else {
        $style->data['youtube']['vq'] = 'large';
      }
      unset($style->data['youtube']['hd']);
      ctools_export_crud_save('vef_video_styles', $style);
    }
  }

  return t('Parameter hd has been converted to vq.');
}

/**
 * Updates naming of 'node' formatter setting to 'content'.
 */
function video_embed_field_update_7008() {
  $instances = field_info_instances();
  foreach ($instances as $entity_type) {
    foreach ($entity_type as $bundle) {
      foreach ($bundle as $instance) {
        $field_info = field_info_field($instance['field_name']);
        if ($field_info['type'] == 'video_embed_field') {
          $update = FALSE;
          foreach ($instance['display'] as &$display) {
            if ($display['type'] == 'video_embed_field_thumbnail') {
              if ($display['settings']['image_link'] == 'node') {
                $display['settings']['image_link'] = 'content';
                $update = TRUE;
              }
              if ($display['settings']['image_style'] == 'none') {
                $display['settings']['image_style'] = '';
                $update = TRUE;
              }
            }
          }
          if ($update) {
            field_update_instance($instance);
          }
        }
      }
    }
  }

  return t("Updated 'node' setting to 'content'");
}

/**
 * Adds new Allowed Providers setting to existing instances.
 */
function video_embed_field_update_7009() {
  $allowed_providers = array_keys(video_embed_get_handlers());

  $instances = field_info_instances();
  foreach ($instances as $entity_type) {
    foreach ($entity_type as $bundle) {
      foreach ($bundle as $instance) {
        $field_info = field_info_field($instance['field_name']);
        if ($field_info['type'] == 'video_embed_field') {
          $instance['settings']['allowed_providers'] = $allowed_providers;
          field_update_instance($instance);
        }
      }
    }
  }

  return t('Updated default instance settings');
}

/**
 * Update styles with empty class parameter.
 */
function video_embed_field_update_7010() {
  drupal_get_schema('vef_video_styles', TRUE);
  ctools_include('export');
  $styles = ctools_export_load_object('vef_video_styles');
  foreach ($styles as $style) {
    foreach ($style->data as &$provider) {
      if (!isset($provider['class'])) {
        $provider['class'] = '';
      }
    }
    ctools_export_crud_save('vef_video_styles', $style);
  }

  return 'Parameter class added to existing styles';
}
