<?php
/**
 * @file
 * Provides a media plugin to search files on the server on the client.
 */


/**
 * Implements hook_media_browser_plugin_info().
 */
function bassets_media_media_browser_plugin_info() {
  $info['bassets'] = array(
    'title' => 'Bassets',
    'class' => 'BassetsRemoteSearch',
  );
  return $info;
}

/**
 * Implements hook_file_download().
 */
function bassets_media_file_download($uri) {
  $path = file_uri_target($uri);
  if (strpos($path, 'bassets_preview/') === 0) {
    // Check that the file exists and is an image.
    if ($info = image_get_info($uri)) {
      return array(
          // Send headers describing the image's size, and MIME-type...
          'Content-Type' => $info['mime_type'],
          'Content-Length' => $info['file_size'],
          // By not explicitly setting them here, this uses normal Drupal // Expires, Cache-Control and ETag headers to prevent proxy or // browser caching of private images.
      );
    }
  }
}

/**
 * Extends the MediaBrowserPlugin class to provide the interface for the
 * remote search.
 */
class BassetsRemoteSearch extends MediaBrowserPlugin {
  protected $providers;

  /**
   * {@inheritDoc}
   */
  public function __construct($info, $params) {
    parent::__construct($info, $params);
    $this->providers = _bassets_scc_connections_load('server');
  }

  /**
   * {@inheritDoc}
   */
  public function access($account = NULL) {
    if (empty($this->providers)) {
      return FALSE;
    }
    return parent::access($account);
  }

  /**
   * {@inheritDoc}
   */
  public function view() {
    $build['#title'] = t('Bassets');
    $build['form'] = drupal_get_form('bassets_media_search_form', $this->params, $this->providers);
    return $build;
  }
}

/**
 * Form for the media selector.
 */
function bassets_media_search_form($form, $form_state, $params, $providers) {
  $form['#providers'] = $providers;
  // Form was submitted -> search button.
  $provider = isset($form_state['input']['provider']) ? $form_state['input']['provider'] : key($providers);
  // Pager.
  $provider = isset($_GET['provider']) ? $_GET['provider'] : $provider;

  if (count($providers) > 1) {
    $options = array();
    foreach ($providers as $provider_name => $conf) {
      $options[$provider_name] = $conf->admin_title;
    }
    $form['provider'] = array(
      '#type' => 'select',
      '#options' => $options,
      '#title' => t('Server'),
      '#default_value' => $provider,
    );
  }
  else {
    $form['provider'] = array(
      '#type' => 'value',
      '#value' => key($providers),
    );
  }

  $form['fulltext_search'] = array(
    '#title' => t('Search'),
    '#type' => 'textfield',
    '#weight' => -3,
  );
  try{
    $client = services_client_connection_get($provider);
    $client->action(BASSETS_SERVER_RESOURCE, 'searchconfig');
    $response = $client->getResponse();
    if (!empty($response->data['form_elements'])) {
      $form['filter_fieldset'] = array(
        '#type' => 'fieldset',
        '#title' => t('Filter'),
        '#collapsible' => TRUE,
        '#collapsed' => TRUE,
        '#weight' => -2,
      );
      $form['filter_fieldset']['filter'] = array('#tree' => TRUE) + $response->data['form_elements'];
    }
  }
  catch (Exception $e) {
    watchdog_exception('bassets_media', $e);
  }
  $form['actions_top'] = array(
    '#type' => 'actions',
    '#weight' => -1,
  );
  $form['actions_top']['search'] = array(
    '#type' => 'button',
    '#value' => t('Search'),
  );
  $page = pager_find_page();
  $keys = isset($form_state['input']['fulltext_search']) ? $form_state['input']['fulltext_search'] : '';
  $keys = isset($_GET['keys']) ? $_GET['keys'] : $keys;

  $limit = 12;
  $offset = $page * $limit;
  if (!empty($form_state['input']) || isset($_GET['keys'])) {
    try{
      $client = services_client_connection_get($provider);
      $fields = array('uuid', 'name', 'base64encoded', 'type', 'url');
      $params = array(
        'keys' => $keys,
        'fields' => $fields,
        'count' => 1,
        'offset' => $offset,
        'limit' => $limit,
      );
      if (!empty($form_state['input']['filter'])) {
        $params['filter'] = array_filter($form_state['input']['filter']);
      }
      $client->get('search_api', 'files_index', $params);
      $response = $client->getResponse();
      if (!empty($response->data)
        && isset($response->data['count']) && (int) $response->data['count'] > 0
        && !empty($response->data['result'])
        ) {
        $files = $response->data['result'];
        pager_default_initialize($response->data['count'], $limit);
        bassets_media_build_result($form, $files);
        $form['pager'] = array(
          '#markup' => theme('pager', array('parameters' => array('keys' => $keys, 'provider' => $provider))),
        );
      }
      else {
        drupal_set_message(t('Did not found any files.'), 'warning', FALSE);
      }
    }
    catch (Exception $e) {
      watchdog_exception('bassets_media', $e);
    }
  }
  $form['actions'] = array(
    '#type' => 'actions',
    '#attributes' => array('class' => array('container-inline')),
  );
  $form['#attached']['js'][] = drupal_get_path('module', 'bassets_media') . '/js/bassets_media.js';

  if (isset($form['bassets']['#type'])) {
    $form['actions']['submit'] = array(
      '#type' => 'submit',
      '#value' => t('Insert'),
    );
  }
  return $form;
}

/**
 * Submit handler for the bassets search form.
 *
 * @see bassets_media_search_form()
 */
function bassets_media_search_form_submit($form, &$form_state) {
  $uuid_entered = $form_state['values']['bassets'];
  if (!empty($uuid_entered)) {
    $files = entity_uuid_load('file', array($uuid_entered));
    if (!empty($files)) {
      $form_state['files'] = $files;
    }
    else {
      $provider_name = isset($form_state['values']['provider']) ? $form_state['values']['provider'] : key($form['#providers']);
      module_load_include('inc', 'bassets_client', 'resources/bassetsclient');
      $status = _bassets_file_pushuuid($uuid_entered, 'public://' . $uuid_entered . '.jpeg', $form['#providers'][$provider_name]->services_client_id);
      if (isset($status['file'])) {
        $form_state['files'][$status['file']->fid] = $status['file'];
      }
    }
  }
  // Redirect the browser with the file id as parameter.
  if (!empty($form_state['files'])) {
    $parameters = array('query' => array('render' => 'media-popup', 'fid' => array_keys($form_state['files'])));
    $form_state['redirect'] = array('media/browser', $parameters);
  }
}

/**
 * Builds the result form element which can be used by the media module.
 */
function bassets_media_build_result(&$form, array $entities) {
  module_load_include('inc', 'media', 'includes/media.browser');
  $dir = file_default_scheme() . '://bassets_preview';
  $writable = file_prepare_directory($dir, FILE_CREATE_DIRECTORY);
  if (!$writable) {
    return;
  }
  $files = $options = array();
  foreach ($entities as $fid => $entity) {
    $image = $entity['base64encoded'];
    $type = $entity['type'];
    $uuid = $entity['uuid'];
    $filename = $entity['name'];
    $url = $entity['url'];
    $uri = $dir . '/' . $uuid . '.' . pathinfo($url, PATHINFO_EXTENSION);
    if (empty($image)) {
      $file = new stdClass();
      $file->filemime = file_get_mimetype($uri);
      $icon_dir = variable_get('media__icon_base_directory', 'public://media-icons') . '/' . variable_get('media__icon_set', 'default');
      $path = file_icon_path($file, $icon_dir);
      if ($path) {
        $image = base64_encode(file_get_contents($path));
      }
    }
    $uri = file_unmanaged_save_data(base64_decode($image), $uri, FILE_EXISTS_REPLACE);
    $file = file_uri_to_object($uri);
    $file->type = $type;
    if (!isset($file->fid)) {
      $file->fid = 0;
    }
    $file->filename = $filename;
    file_entity_metadata_fetch_image_dimensions($file);
    media_browser_build_media_item($file);
    $options[$uuid] = '<li>' . $file->preview . '</li>';
    $files[$uri] = $file;
  }
  $form['bassets'] = array(
    '#type' => 'radios',
    '#title' => t('Results'),
    '#options' => $options,
    '#prefix' => '<div class="media-display-thumbnails media-clear clearfix"><ul id="media-browser-library-list" class="media-list-thumbnails">',
    '#suffix' => '</ul></div>',
  );
  // Add the files to JS so that they are accessible inside the browser.
  drupal_add_js(array('media' => array('files' => $files)), 'setting');
}
