<?php

/**
 * @file
 * Provide statistics for published LOM-CH descriptions.
 *
 * The Archibald Statistics module allows editors to see statistics for
 * published LOM-CH descriptions. These statistics are only available to the
 * partners that have access to a given description. Statistics are made
 * available via a custom Views plugin. This means a view can be used to see
 * the statistics data.
 */

/**
 * Implements hook_menu_alter().
 */
function archibald_stats_menu_alter(&$items) {
  if (isset($items['admin/archibald/description/statistics'])) {
    // We do the same as in archibald_menu_alter().
    $items[$path]['title callback'] = '_archibald_title_callback';
    $items[$path]['title arguments'] = array(
      $items[$path]['title'],
      array(),
      array('context' => 'archibald:views'),
    );
  }
}

/**
 * Implements hook_permission().
 */
function archibald_stats_permission() {
  return array(
    'access archibald_stats statistics' => array(
      'title' => t("Access Archibald statistics"),
    ),
  );
}

/**
 * Implements hook_theme().
 */
function archibald_stats_theme() {
  return array(
    'archibald_stats_pager_mini' => array(
      'variables' => array('tags' => array(), 'element' => 0, 'parameters' => array()),
    ),
  );
}

/**
 * Implements hook_views_api().
 */
function archibald_stats_views_api() {
  return array(
    'api' => 3,
  );
}

/**
 * Implements of hook_views_plugins().
 */
function archibald_stats_views_plugins() {
  return array(
    'module' => 'archibald_stats',
    'query' => array(
      'archibald_stats_views_query' => array(
        'title' => t("Archibald Statistics Query"),
        'help' => t("Query that allows you to view Archibald statistics using the dsb REST API."),
        'handler' => 'archibald_stats_views_query',
        'parent' => 'views_query',
      ),
    ),
    'pager' => array(
      'archibald_stats_pager_mini' => array(
        'title' => t("Archibald Statistics Pager"),
        'help' => t("Special pager for Archibald Statistics Query"),
        'handler' => 'archibald_stats_pager_mini',
        'parent' => 'mini',
        'uses options' => TRUE,
      ),
    ),
  );
}

/**
 * Implements of hook_views_data().
 */
function archibald_stats_views_data() {
  $data = array();

  $data['archibald_stats']['table']['group'] = t("Archibald statistics");
  $data['archibald_stats']['table']['base'] = array(
    'query class' => 'archibald_stats_views_query',
    'title' => t("Archibald statistics"),
    'help' => t("Displays Archibald statistics using views."),
  );

  $data['archibald_stats']['lomId'] = array(
    'title' => t("LOM ID"),
    'help' => t("The LOM ID of the published description."),
    'field' => array(
      'handler' => 'archibald_stats_base_field',
    ),
    'filter' => array(
      'handler' => 'archibald_stats_lomid_filter',
    ),
    'argument' => array(
      'handler' => 'archibald_stats_lomid_argument',
    ),
  );

  $data['archibald_stats']['node_title'] = array(
    'title' => t("Description title"),
    'help' => t("The title of the published description."),
    'field' => array(
      'handler' => 'archibald_stats_node_field',
    ),
  );

  $data['archibald_stats']['node_nid'] = array(
    'title' => t("Description NID"),
    'help' => t("The node NID of the published description."),
    'field' => array(
      'handler' => 'archibald_stats_node_field',
    ),
    'argument' => array(
      'handler' => 'archibald_stats_nid_argument',
    ),
  );

  $data['archibald_stats']['views'] = array(
    'title' => t("View count"),
    'help' => t("The number of times the description was viewed."),
    'field' => array(
      'handler' => 'archibald_stats_base_field',
    ),
  );

  $data['archibald_stats']['year'] = array(
    'title' => t("Year"),
    'help' => t("The year to which the description statistic applies."),
    'field' => array(
      'handler' => 'archibald_stats_base_field',
    ),
  );

  $data['archibald_stats']['month'] = array(
    'title' => t("Month"),
    'help' => t("The month to which the description statistic applies."),
    'field' => array(
      'handler' => 'archibald_stats_base_field',
    ),
  );

  $data['archibald_stats']['day'] = array(
    'title' => t("Day"),
    'help' => t("The day to which the description statistic applies."),
    'field' => array(
      'handler' => 'archibald_stats_base_field',
    ),
  );

  $data['archibald_stats']['date'] = array(
    'title' => t("Date"),
    'help' => t("The date to which the description statistic applies."),
    'field' => array(
      'handler' => 'archibald_stats_date_field',
    ),
  );

  $data['archibald_stats']['partner'] = array(
    'title' => t("Partner"),
    'help' => t("Filter by partner"),
    'field' => array(
      'handler' => 'archibald_stats_partner_field',
    ),
    'filter' => array(
      'handler' => 'archibald_stats_partner_filter',
    ),
  );

  $data['archibald_stats']['from_to'] = array(
    'title' => t("From/to dates"),
    'help' => t("Filter by date span"),
    'filter' => array(
      'handler' => 'archibald_stats_date_filter',
    ),
  );

  $data['archibald_stats']['aggregation_method'] = array(
    'title' => t("Aggregation method"),
    'help' => t("Aggregate by day, month, or year"),
    'filter' => array(
      'handler' => 'archibald_stats_aggregation_method_filter',
    ),
  );

  return $data;
}

/**
 * Implements hook_form_FORM_ID_alter() for views_exposed_form().
 */
function archibald_stats_form_views_exposed_form_alter(&$form, $form_state) {
  $view = $form_state['view'];
  if ($view->name == 'archibald_stats') {
    if (!empty($form['from_to']['max']['#title'])) {
      $form['from_to']['max']['#title'] = t("To", array(), array('context' => 'archibald_stats:views'));
    }
  }
}

/**
 * Implements hook_views_pre_view().
 */
function archibald_stats_views_pre_view(&$view, &$display_id, &$args) {
  // Must we display a 'view on portal' link?
  if ($view->name == 'archibald_lomch_descriptions' && $display_id == 'published') {
    module_load_include('inc', 'archibald', 'includes/archibald.views');

    // Fetch the display handler.
    $handler = &$view->display[$display_id]->handler;

    // Add our field definition. See
    // archibald_views_custom_text_field_defaults() for the defaults concerning
    // custom text field.
    $handler->options['fields']['view_stats'] = archibald_views_custom_text_field_defaults(
      'view_stats',
      t("view stats", array(), array('context' => 'archibald_stats:views'))
    );

    // Alter the default settings a little bit.
    $handler->options['fields']['view_stats']['alter'] = array(
      'make_link' => TRUE,
      'path' => "node/[nid]/statistics",
    ) + $handler->options['fields']['view_stats']['alter'];
  }
}

/**
 * Theme callback for archibald_stats_pager_mini.
 *
 * This is almost a verbatim copy of theme_views_mini_pager().
 *
 * @see theme_views_mini_pager()
 */
function theme_archibald_stats_pager_mini($vars) {
  global $pager_page_array, $pager_total;

  $tags = $vars['tags'];
  $element = $vars['element'];
  $parameters = $vars['parameters'];

  // current is the page we are currently paged to
  $pager_current = $pager_page_array[$element] + 1;
  // max is the maximum page number
  $pager_max = $pager_total[$element];
  // End of marker calculations.

  if ($pager_total[$element] > 1) {
    $li_previous = theme('pager_previous',
      array(
        'text' => (isset($tags[1]) ? $tags[1] : t('‹‹')),
        'element' => $element,
        'interval' => 1,
        'parameters' => $parameters,
      )
    );
    if (empty($li_previous)) {
      $li_previous = "&nbsp;";
    }

    $li_next = theme('pager_next',
      array(
        'text' => (isset($tags[3]) ? $tags[3] : t('››')),
        'element' => $element,
        'interval' => 1,
        'parameters' => $parameters,
      )
    );

    if (empty($li_next)) {
      $li_next = "&nbsp;";
    }

    $items[] = array(
      'class' => array('pager-previous'),
      'data' => $li_previous,
    );

    $items[] = array(
      'class' => array('pager-next'),
      'data' => $li_next,
    );

    return theme('item_list',
      array(
        'items' => $items,
        'title' => NULL,
        'type' => 'ul',
        'attributes' => array('class' => array('pager')),
      )
    );
  }
}

/**
 * Helper function to load partner statistics.
 *
 * @param int $partner_id
 * @param int $from
 *    From timestamp.
 * @param int $to
 *    To timestamp.
 * @param string $aggregation_method
 *    (optional) Aggregation method. Either "day", "month" or "year". Defaults
 *    to "day".
 * @param string $lom_id
 *    (optional) Filter by a specific LOM ID. Defaults to null, which means all
 *    descriptions are shown.
 * @param int $limit
 *    (optional) Limit the number of results. Defaults to null, which means we
 *    use the default value of the api.
 * @param int $offset
 *    (optional) By how many results to offset the results. Defaults to 0.
 *
 * @return array
 */
function archibald_stats_fetch($partner_id, $from, $to, $aggregation_method = 'day', $lom_id = NULL, $limit = NULL, $offset = 0) {
  $partner = archibald_partner_load($partner_id);
  $client = archibald_get_client_based_on_config($partner_id);
  return $client->loadPartnerStatistics(
    $partner->partner_username[LANGUAGE_NONE][0]['value'],
    date('Y-m-d', $from),
    date('Y-m-d', $to),
    $aggregation_method,
    $lom_id,
    $limit,
    $offset
  );
}
