<?php

/**
 * TODO.
 *
 * @param 
 *   TODO
 * @return
 *   TODO.
 */
function vote_admin_results_page_score($form, &$form_state, $pool, $function) {
  drupal_set_title(t('Results for @pool (@function)', array('@pool' => $pool->name, '@function' => vote_function_title($function))));

  $query = db_select(vote_function_table($function), 'r')->extend('PagerDefault')->extend('TableSort');
  
  vote_admin_results_filter_form($form, $form_state, $query, $pool->pool, $function);

  $header = array(
    'type' => array('data' => t('Entity type'), 'field' => 'r.entity_type'),
    'title' => array('data' => t('Entity'), 'field' => 'r.entity_id'),
    'choice' => array('data' => t('Choice'), 'field' => 'r.choice'),
    'value' => array('data' => t('Score'), 'field' => 'r.value'),
    'created' => array('data' => t('Created'), 'field' => 'r.created', 'sort' => 'desc'),
  );

  $query = $query->fields('r', array('rid', 'pool', 'entity_type', 'entity_id', 'choice', 'value', 'created'))
    ->condition('function', $function)
    ->condition('pool', $pool->pool)
    ->limit(50)
    ->orderByHeader($header)
    ->execute()->fetchAll();  
    
  $options = $results = $groups = array();
  
  foreach ($query as $item) {
    $group = vote_rid($item, $function);
    
    if (!isset($groups[$group])) {
      $groups[$group] = vote_function($function, $item);
    }

    $groups[$group]->value[$item->choice] = $item->value;
  }

  if (!empty($query)) { 
    $entities = vote_attached_entity_load_multiple($results, 'rid');    
    $destination = drupal_get_destination();
    
    foreach ($query as $result) {
      $entity = isset($entities[$result->rid]) ? $entities[$result->rid] : NULL;
      $info = entity_get_info($result->entity_type);
      $group = vote_rid($result, $function);
      $choice = (object) array('value' => $result->choice);
      $type = $result->entity_type == 'node' ? node_type_get_name($entity) : '';
      $type = $info['label'] . (!empty($type) ?  ' (' . $type . ')' : '');
      
      $options[$result->rid] = array(
        'type' => $type,
        'choice' => $pool->render($choice),
        'value' => $groups[$group]->render($result->choice),      
        'created' => array(
          'data' => array(
            '#type' => 'markup',
            '#markup' => format_date($result->created, 'short'),
          ),
        ),
      );
  
      if (isset($entity)) {
        $uri = entity_uri($result->entity_type, $entity);
        $options[$result->rid]['title'] = array(
          'data' => array(
            '#type' => 'link',
            '#title' => entity_label($result->entity_type, $entity),
            '#attributes' => array('title' => t('View entity.')),
            '#href' => url($uri['path'], array_merge($uri['options'], array('absolute' => TRUE))),
          ),
        );
      } 
      else {
        $options[$result->rid]['title'] = t('deleted');
      }     
    }
  }

  $form['items'] = array(
    '#type' => 'table',
    '#header' => $header,
    '#empty' => t('No votes available.'),
  );

  $form['pager'] = array('#markup' => theme('pager'));
  
  return $form;
}

/**
 * TODO.
 *
 * @param 
 *   TODO
 * @return
 *   TODO.
 */
function vote_admin_results_page_default($form, &$form_state, $pool, $function) {
  drupal_set_title(t('Results for @pool (@function)', array('@pool' => $pool->name, '@function' => vote_function_title($function))));
    
  $query = db_select(vote_function_table($function), 'r')->extend('PagerDefault')->extend('TableSort');
  
  vote_admin_results_filter_form($form, $form_state, $query, $pool->pool, $function);

  $header = array(
    'type' => array('data' => t('Entity type'), 'field' => 'r.entity_type'),
    'title' => array('data' => t('Entity'), 'field' => 'r.entity_id'),
    'value' => array('data' => t('Value'), 'field' => 'r.value'),
    'created' => array('data' => t('Created'), 'field' => 'r.created', 'sort' => 'desc'),
  );

  $query = $query->fields('r', array('rid', 'pool', 'entity_type', 'entity_id', 'value', 'created'))
    ->condition('function', $function)
    ->condition('pool', $pool->pool)
    ->limit(50)
    ->orderByHeader($header)
    ->execute();  

  $rows = $results = array();
  
  foreach ($query as $item) {
    $results[$item->rid] = vote_function($function, $item);
    $results[$item->rid]->rid = $item->rid;
    $results[$item->rid]->value = $item->value;
    $results[$item->rid]->created = $item->created;
  }
  
  if (!empty($results)) { 
    $entities = vote_attached_entity_load_multiple($results, 'rid');    
    $destination = drupal_get_destination();
    
    foreach ($results as $result) {
      $entity = isset($entities[$result->rid]) ? $entities[$result->rid] : NULL;
      $info = entity_get_info($result->entity_type);
      $type = node_type_get_name($entity);
      $type = $info['label'] . ($result->entity_type == 'node' && !empty($type) ?  ' (' . $type . ')' : '');
          
      $rows[$result->rid] = array(
        'type' => $type,    
      );
  
      if (isset($entity)) {
        $uri = entity_uri($result->entity_type, $entity);
        $rows[$result->rid]['title'] = array(
          'data' => array(
            '#type' => 'link',
            '#title' => entity_label($result->entity_type, $entity),
            '#attributes' => array('title' => t('View entity.')),
            '#href' => url($uri['path'], array_merge($uri['options'], array('absolute' => TRUE))),
          ),
        );
      } 
      else {
        $rows[$result->rid]['title'] = t('deleted');
      } 
      
      $rows[$result->rid]['value'] = $result->render();
      $rows[$result->rid]['created'] = array(
        'data' => array(
          '#type' => 'markup',
          '#markup' => format_date($result->created, 'short'),
        ),
      );
    }
  }

  $form['items'] = array('#markup' => theme('table', array('header' => $header, 'rows' => $rows)));
  $form['pager'] = array('#markup' => theme('pager'));
  
  return $form;
}

/**
 * TODO.
 *
 * @param 
 *   TODO
 * @return
 *   TODO.
 */
function vote_admin_results_filter_form(&$form, &$form_state, &$query, $pool, $function) {
  $key = 'vote_results_' . $pool . '_' . $function;
  $form_state['pool'] = $pool;
  $form_state['function'] = $function;
  
  $session = isset($_SESSION[$key]) ? $_SESSION[$key] : array(); 
  $filters = module_invoke_all('vote_results_filters', $pool, $function);
  $and = FALSE;
  
  $form['filters'] = array(
    '#type' => 'fieldset',
    '#title' => t('Show only items where'),
    '#theme' => 'exposed_filters__vote',
  );
  
  foreach ($session as $key => $filter) {    
    list($type, $value) = $filter;
    
    if (isset($filters[$type]['options'][$value])) {
      $args = array('%property' => $filters[$type]['title'], '%value' => $filters[$type]['options'][$value]);
      
      if ($and) {
        $form['filters']['current'][] = array('#markup' => t('and where %property is %value', $args));
      } 
      else {
        $and = TRUE;
        $form['filters']['current'][] = array('#markup' => t('where %property is %value', $args));
      }
    
      $query->condition($filters[$type]['condition'], $value);
      
      unset($filters[$type]);
    } 
    else {
      unset($session[$key]);
    }  
  }

  $form['filters']['status'] = array(
    '#type' => 'container',
    '#attributes' => array('class' => array('clearfix')),
    '#prefix' => $and && !empty($filters) ? '<div class="additional-filters">' . t('and where') . '</div>' : '',
  );
  
  $form['filters']['status']['filters'] = array(
    '#type' => 'container',
    '#attributes' => array('class' => array('filters')),
  );
  
  foreach ($filters as $key => $filter) {
    $form['filters']['status']['filters'][$key] = array(
      '#type' => 'select',
      '#options' => $filter['options'],
      '#title' => $filter['title'],
      '#default_value' => '[any]',
    );
  }

  $form['filters']['status']['actions'] = array(
    '#type' => 'actions',
    '#attributes' => array('class' => array('container-inline')),
  );
  
  if (!empty($filters)) {
    $form['filters']['status']['actions']['submit'] = array(
      '#type' => 'submit',
      '#value' => !empty($session) ? t('Refine') : t('Filter'),
    );
  }
  
  if (!empty($session)) {
    $form['filters']['status']['actions']['undo'] = array('#type' => 'submit', '#value' => t('Undo'));
    $form['filters']['status']['actions']['reset'] = array('#type' => 'submit', '#value' => t('Reset'));
  }
  
  $form['#submit'][] = 'vote_admin_results_filter_form_submit';
}

/**
 * TODO.
 *
 * @param 
 *   TODO
 * @return
 *   TODO.
 */
function vote_admin_results_filter_form_submit($form, &$form_state) {
  $pool = $form_state['pool'];
  $function = $form_state['function'];
  $filters = module_invoke_all('vote_results_filters', $pool, $function);
  $key = 'vote_results_' . $pool . '_' . $function;
  
  switch ($form_state['values']['op']) {
    case t('Filter'):
    case t('Refine'):
      foreach ($filters as $filter => $options) {
        if (isset($form_state['values'][$filter]) && $form_state['values'][$filter] != '[any]') {
          $value = $form_state['values'][$filter];
          $options = form_options_flatten($filters[$filter]['options']);

          if (isset($options[$value])) {
            $_SESSION[$key][] = array($filter, $value);
          }
        }
      }
      break;
    case t('Undo'):
      array_pop($_SESSION[$key]);
      break;
    case t('Reset'):
      $_SESSION[$key] = array();
      break;
  }
}