<?php
// $Id$

/**
 * @file
 *
 */

function incubator_events_views_data_alter(&$data) {
  if (module_exists('views_date_format_sql')) {
    $data['field_data_field_event_date']['field_event_date_value']['field'] = array(
      'table' => 'field_data_field_event_date',
      'handler' => 'views_date_format_sql_handler_field_date',
      'click sortable' => 1,
      'additional fields' => array(),
      'entity_tables' => array(
        'node' => 'node',
        'node_revision' => 'node',
      ),
      'element_type' => 'div',
      'is revision' => 0,
    );
  }
}

function incubator_events_views_query_alter(&$view, &$query) {

  //============================================================================
  // ACTIVITIES VIEW
  // 
  // The activities view organizes and groups upcoming events by day, and to do
  // this it uses the date_format_sql module as well as some tricks and hacks.
  //
  // There are two fields retrieved for the date, both based on the column
  // field_data_field_event_date_field_event_date_value:
  //
  // field_data_field_event_date_field_event_date_value, or "Day"
  // is the named day of the week, e.g. Sunday.  It is the date that is displayed.
  //
  // field_data_field_event_date_field_event_date_value_1 or "Day of week"
  // is the numerical day of the week, and is used for sorting the events, since
  // if the name were used, they would not sort according to the order of the days
  // in the week.
  if ($view->name == 'activities_upcoming_events' && in_array($view->current_display, array('default', 'page'))) {
    // Since date fields retrieve separate values for each occurrence of repeating events,
    // we must remove the date_delta fields from the query in order for the grouping to work.
    unset($query->fields['field_data_field_event_date_delta']);
    unset($query->fields['date_delta_date_filter']);
    // Also, for pgsql support, we must change the formatting string for the numerical day of week field.
    $replacement = db_driver() == 'pgsql' ? 'D' : '%w';
    $query->fields['field_data_field_event_date_field_event_date_value_1']['field'] =
      str_replace("'w'", "'$replacement'", $query->fields['field_data_field_event_date_field_event_date_value_1']['field']);
    // Finally, we must add the sort to the query, and it doesn't work to add it
    // in the views interface.
    array_unshift($query->orderby, array(
      'field' => 'field_data_field_event_date_field_event_date_value_1',
      'direction' => 'ASC'
    ));
  }
  
  //============================================================================
  // UPCOMING EVENTS VIEW
  elseif($view->name == 'incubator_events') {
    
    // On the calendar we trigger logic for showing Baha'i Holy Days
    // and add css and js for print buttons.
    if ($view->current_display == 'calendar') {
      incubator_events_show_bahai_calendar();
      drupal_add_css(drupal_get_path('module', 'incubator_events') . '/css/printable-calendar.css');
      drupal_add_js(drupal_get_path('module', 'incubator_events') . '/js/printable-calendar.js');
    }
    
    // We alter the title for ical feeds, so that it is identified for subscribers.
    elseif ($view->current_display == 'ical_feed_term') {
      $view->build_info['title'] = variable_get('site_name', '');
      if (!empty($view->args[0]) && $view->args[0] != 'all') {
        $view->build_info['title'] .= ' : %1';
      }
    }
  }
  
  //============================================================================
  // Restrict to events that have no time data or are within a time window
  elseif($view->name == 'map' || $view->name == 'incubator_regular_events') {
    $query->add_where_expression(0, "((SELECT ned.field_event_date_value FROM {field_data_field_event_date} ned WHERE ned.revision_id = node.vid LIMIT 0,1) IS NULL "
        . "OR (SELECT ned.field_event_date_value FROM {field_data_field_event_date} ned WHERE ned.revision_id = node.vid AND ned.field_event_date_value > :time AND ned.field_event_date_value < :time2 LIMIT 0,1) IS NOT NULL)", 
        array(':time' => strtotime('-6 hours'), ':time2' => strtotime('+3 months')));
  }
}

/**
 * Implements hook_views_pre_view().
 * 
 * Set grouping options for the regular events view when viewing the taxonomy term by which the events are primarily grouped.
 * Check the description of the incubator_regular_events view in hook_views_default_views.
 */
function incubator_events_views_pre_view(&$view, $display_id, $args) {
  if ($view->name == 'incubator_regular_events' && !empty($args) && $grouping = $view->display_handler->options['style_options']['grouping']['0']) {
    // ^ we only want to change the view if there is a grouping field
    
    if ($grouping['field'] != 'address' && is_numeric($args[0]) && $term = taxonomy_term_load($args[0])) {
      // ^ only change the view if not grouping by address AND viewing a term page...
      
      if ($term->vocabulary_machine_name == str_replace('field_', '', $grouping['field'])) {
        // ^ ...and only of the grouped vocabulary. this is a little brittle since it relies fields being named the same as taxonomy vocabularies, e.g. field_tags = tags taxonomy.
        
        $grouping_choices = incubator_events_get_grouping_fields();
        $choice = $grouping_choices['secondary']; 
        // ^ The primary grouping should be taken care of in hook_views_default_views_alter().

        unset($view->display_handler->options['fields'][$grouping_choices{'primary'}]);
        unset($view->display_handler->options['relationships'][$grouping_choices{'primary'}]);
        // ^ Unset the taxonomy field and relationship for the primary grouping, to avoid issues.
        
        if (strpos($choice, 'field_') !== 0) {
          // Disable term grouping if the choice is address or null
          unset($view->display_handler->options['sorts']['weight']);
          $view->display_handler->options['arguments']['term_node_tid_depth_modifier']['summary_options']['grouping'] = FALSE;
          if ($choice == 'address') {
            $view->display_handler->options['style_options']['grouping'][0] = array(
              'field' => 'address',
              'rendered' => 1,
              'rendered_strip' => 1,
            );
          }
          else {
            $view->display_handler->options['style_options']['grouping'] = FALSE;
            unset($view->display_handler->options['fields']['address']);
            unset($view->display_handler->options['sorts']['city']);
          }
        }
        
        else {
          $choice_tid = $choice . '_tid';
          $view->display_handler->options['fields'][$choice]['group_rows'] = FALSE;
          $view->display_handler->options['relationships'][$choice_tid]['id'] = $choice_tid;
          $view->display_handler->options['relationships'][$choice_tid]['table'] = 'field_data_' . $choice;
          $view->display_handler->options['relationships'][$choice_tid]['field'] = $choice_tid;
          $view->display_handler->options['style_options']['grouping'][0]['field'] = $choice;
          $view->display_handler->options['arguments']['term_node_tid_depth_modifier']['summary_options']['grouping'][0]['field'] = $choice;
          $view->display_handler->options['sorts']['weight']['relationship'] = $choice_tid;
        }
      }        
    }
  }
}

/**
 * Implements hook_views_pre_render(). This will remove the feed icon if the 
 * upcoming events are empty.
 * 
 * @param object $view
 */
function incubator_events_views_pre_render(&$view) {
  if ($view->name == 'incubator_events' && empty($view->result)) {
    unset($view->feed_icon);
  }
}

function incubator_events_show_bahai_calendar() {
  if (variable_get('incubator_events_show_bahai_calendar', incubator_is_bahai_site())) {
    global $language;
    $years = array(
      date('Y') - 1,
      date('Y'),
      date('Y') + 1,
    );
    $events = array();
    $years_to_get = array();
    foreach ($years as $year) {
      if ($cache = cache_get("incubatorbahaicalendar:$year:$language->language")) {
        $events = array_merge($events, $cache->data);
      }
      else {
        $years_to_get[] = $year;
      }
    }
    if (!empty($years_to_get)) {
      module_load_include('inc', 'incubator_events', 'incubator_events.bahaicalendar');
      foreach($years_to_get as $year) {
        $new_events = array();
        if ($bahaical = _incubator_events_get_bahaicalendar($year)) {
          // Create event list for calendar
          foreach ($bahaical as $var => $cal) {
            foreach ($cal as $day => $name) {
              $events[] = $new_events[] = array(
                'title' => $name,
                'start' => "$year-$day",
                'className' => "bahaical $var",
              );
              
            }
          }
          cache_set("incubatorbahaicalendar:$year:$language->language", $new_events);
        }
      }
    }
    drupal_add_css(drupal_get_path('module', 'incubator_events') . '/css/bahaicalendar.css');
    drupal_add_js(array('incubatorBahaiCalendar' => array(
      'events' => $events,
      'editable' => FALSE,
      'allDayDefault' => TRUE,
      'ignoreTimezone' => TRUE,
    )), 'setting');
  }
}

