<?php
/**
 * @file
 * Code for the Course planner feature.
 */

include_once 'courseplanner.features.inc';

/**
 * Implements hook_menu().
 */
function courseplanner_menu() {
  return array(
    'admin/config/system/courseplanner' => array(
      'title' => 'Course planner',
      'description' => 'Setting for the Course planner module.',
      'page callback' => 'drupal_get_form',
      'page arguments' => array('courseplanner_admin_form'),
      'access arguments' => array('administer site configuration'),
    ),
  );
}

/**
 * Implements hook_ctools_plugin_directory().
 */
function courseplanner_ctools_plugin_directory($module, $plugin) {
  if ($module == 'ctools' && !empty($plugin)) {
    return "includes/$plugin";
  }
}

/**
 * Administration form for the Course planner module.
 *
 * @return array
 *   A form array.
 */
function courseplanner_admin_form($form, &$form_state) {
  $form = array(
    'courseplanner_hide_bookmarks' => array(
      '#type' => 'checkbox',
      '#title' => t('Hide the Bookmarks views, provided by the Flag module.'),
      '#default_value' => variable_get('courseplanner_hide_bookmarks', TRUE),
    ),
  );
  return system_settings_form($form);

}

/**
 * Implements hook_date_format_types().
 */
function courseplanner_date_formats() {
  return array(
    array(
      'type' => 'courseplanner_week',
      'format' => 'W',
      'locales' => array(),
    ),
    array(
      'type' => 'courseplanner_daytime',
      'format' => 'D, H:i',
      'locales' => array(),
    ),
    array(
      'type' => 'courseplanner_export',
      'format' => 'U',
      'locales' => array(),
    ),
  );
}

function courseplanner_date_format_types() {
  return array(
    'courseplanner_week' => t('Week number'),
    'courseplanner_daytime' => t('Day and time'),
    'courseplanner_export' => t('Courseplanner export format'),
  );
}

/**
 * Builds an options array with most relevant Course planner items.
 *
 * This function checks for Course planner items of a given type, and returns
 * an array suitable for drop-down lists. First any favourites will be checked
 * and if none are found the items created by the acting will be returned. If no
 * such items are found, all items of the matching type will be returned.
 *
 * @param $type
 *   The machine name of the content type: cp_outline, cp_offering, cp_section
 *   or cp_resource.
 * @return
 *   An array keyed by the node IDs, and the titles as lables.
 */
function courseplanner_get_items_as_options($type) {
  $options = array();

  // First, try to get favourites.
  $results = views_get_view_result('cp_item_lists', 'cp_my_favourites', $type);
  // If none are found, get items created by acting user.
  if (count($results) == 0) {
    global $user;
    $results = views_get_view_result('cp_item_lists', 'items_per_user', $type, $user->uid);
  }
  // If still none are found, get all items of the specified type.
  if (count($results) == 0) {
    $results = views_get_view_result('cp_item_lists', 'items_per_user', $type);
  }

  foreach ($results as $result) {
    $options[$result->nid] = $result->node_title;
  }

  return $options;
}

// Everything below here is UX improvements only -- the module will work fine
// without these functions (from a technical standpoint), but it will be
// difficult to understand some parts of the site, and a lot of hidden form
// elements will start to show.

/**
 * Implements hook_views_bulk_operations_form_alter().
 *
 * Performs changes to the VBO form used to admininster lessons, such as moving
 * the action form to the bottom of the admin view.
 */
function courseplanner_views_bulk_operations_form_alter(&$form, &$form_state, $vbo) {
  if ($form['#form_id'] == 'views_form_cp_course_offering_lessons_cp_lessons_admin' && isset($form['select'])) {
    $form['select']['#type'] = 'container';

    // Hide some advanced actions in a fieldset.
    $advanced_actions = array(
      'rules_component::rules_cp_fill_lessons',
      'rules_component::rules_cp_repeat_lesson',
      'rules_component::rules_cp_copy_lessons_to_weeks',
      'rules_component::rules_cp_shift_lessons',
    );
    $form['select']['advanced'] = array(
      '#type' => 'fieldset',
      '#title' => t('Advanced actions'),
      '#collapsible' => TRUE,
      '#collapsed' => TRUE,
    );
    foreach ($advanced_actions as $action) {
      if (isset($form['select'][$action])) {
        $form['select']['advanced'][$action] = $form['select'][$action];
        $form['select'][$action]['#access'] = FALSE;
      }
    }

    // Clone the action buttons and display them below the list as well.
    $form['select_below'] = $form['select'];
    $form['select_below']['#weight'] = 100;

    // Hide the advanced actions in the form above the list.
    $form['select']['advanced']['#access'] = FALSE;
  }

  // If the user is about to select a course outline, load a select list.
  if ($outline = &$form['parameter']['outline']['settings']['outline']) {
    $outline['#type'] = 'select';
    $outline['#options'] = courseplanner_get_items_as_options('cp_outline');
  }

  // If the user is about to select a course section, load a select list.
  if ($section = &$form['parameter']['section']['settings']['section']) {
    $section['#type'] = 'select';
    $section['#options'] = courseplanner_get_items_as_options('cp_section');
  }
  // If the user is about to select weeks to copy lessons to, tweak the UI.
  if ($weeks = &$form['parameter']['weeks']['settings']['weeks']) {
    $form['parameter']['weeks']['settings']['help']['#access'] = FALSE;
    $form['parameter']['weeks']['settings']['weeks']['#description'] = t('Enter week numbers, one per line. If the week is not the closest upcoming week with that number, you can enter the year as well (eg. "2013 4").');
  }
}

/**
 * Implements hook_form_FORM_ID_alter().
 *
 * Alters the course section form, to remove most parts of the field collection
 * forms. Everything except reordering the items is managed from the node view
 * page.
 */
function courseplanner_form_cp_section_node_form_alter(&$form, &$form_state) {
  // If the first resource list is empty, hide the whole field for resource
  // lists. Adding new lists is done elsewhere.
  if (is_null($form['cp_resource_lists'][LANGUAGE_NONE][0]['cp_list_name'][LANGUAGE_NONE][0]['value']['#default_value'])) {
    $form['cp_resource_lists']['#access'] = FALSE;
  }

  // Hide the promote box, resource reference and remove button for each field
  // collection item.
  $delta = 0;
  while (isset($form['cp_resource_lists'][LANGUAGE_NONE][$delta])) {
    $form['cp_resource_lists'][LANGUAGE_NONE][$delta]['cp_list_promote']['#access'] = FALSE;
    $form['cp_resource_lists'][LANGUAGE_NONE][$delta]['cp_resource']['#access'] = FALSE;
    $form['cp_resource_lists'][LANGUAGE_NONE][$delta]['remove_button']['#access'] = FALSE;
    $delta++;
  }
  // Hide the button for adding more field collection items.
  $form['cp_resource_lists'][LANGUAGE_NONE]['add_more']['#access'] = FALSE;
}

/**
 * Implements hook_form_FORM_ID_alter().
 *
 * Alters the lesson form, to hide the course offering reference.
 */
function courseplanner_form_cp_lesson_node_form_alter(&$form, &$form_state) {
  $form['cp_course_offering']['#access'] = FALSE;
}

/**
 * Implements hook_form_FORM_ID_alter().
 *
 * Alters forms provided by Rules panes, to allow better UX.
 */
function courseplanner_form_rules_panes_render_form_alter(&$form, &$form_state) {
  // Alters the form used to create new lessons, and switches out the textfield
  // for a date popup.
  if ($form['component']['#value'] == 'rules_add_new_lesson') {
    $form['parameter']['date']['settings']['date']['#title_display'] = 'invisible';
    $form['parameter']['date']['settings']['date']['#type'] = 'date_popup';
    $form['parameter']['date']['settings']['date']['#description'] = '';
    $form['parameter']['date']['settings']['date']['#date_format'] = 'Y-m-d H:i';
    $form['parameter']['date']['settings']['date']['#date_increment'] = 5;
  }

  // Alters the form used to add sections to a course outline.
  if ($form['component']['#value'] == 'rules_cp_create_and_add_sections_to_outline') {
    $form['parameter']['titles']['settings']['titles']['#description'] = t('Add the name of sections, one per line. If you want a size larger than one, add size separated by a comma (eg. "My section, 5").');
  }

  // Alters the form used to add lessons to a course offering.
  if ($form['component']['#value'] == 'rules_cp_lessons_import') {
    $form['parameter']['dates']['settings']['dates']['#description'] = t('Add lesson times, one per line, on the form "start time, end time/duration" (eg. "2013-02-04 8:20, 60 minutes").<br />
      Both start and end time can be added in absolute format (eg. "2013-02-04 08:20") or in relative format (eg. "today 8:20"). End time will be relative the start time, while the start time will be relative the current time.<br />
      End times should be separated from the start time with a comma.<br />
      Finally, you can provide a lesson with a default title by adding a line "# My lesson title" above it.');
  }
}

/**
 * Implements hook_form_FORM_ID_alter().
 *
 * Hides the pre-filled cp_offering_outline.
 */
function courseplanner_form_cp_offering_node_form_alter(&$form, &$form_state) {
  $form['cp_offering_outline']['#access'] = FALSE;
}

/**
 * Implements hook_views_default_views_alter().
 *
 * Disables the bookmarks view provided by the Flag module.
 */
function courseplanner_views_default_views_alter($views) {
  if (isset($views['flag_bookmarks'])) {
    // You can set variable 'courseplanner_hide_bookmarks' to FALSE to stop
    // disabling the bookmarks view.
    if (variable_get('courseplanner_hide_bookmarks', TRUE)) {
      $views['flag_bookmarks']->disabled = TRUE;
    }
  }
  if (isset($views['flag_bookmarks_tab'])) {
    if (variable_get('courseplanner_hide_bookmarks', TRUE)) {
      $views['flag_bookmarks_tab']->disabled = TRUE;
    }
  }
}

/**
 * Implements hook_flag_alter().
 *
 * Hides the default 'bookmarks' flag by unsetting the content types it is used
 * on.
 */
function courseplanner_flag_alter($flag) {
  if ($flag->name == 'bookmarks') {
    // You can set variable 'courseplanner_hide_bookmarks' to FALSE to stop
    // disabling the bookmarks flag.
    if (variable_get('courseplanner_hide_bookmarks', TRUE)) {
      $flag->types = array();
    }
  }
}
