<?php

/**
 * Implementation of hook_ctools_plugin_directory().
 */
function context_ui_ctools_plugin_directory($module, $plugin) {
  if ($module == 'ctools' && $plugin == 'export_ui') {
    return 'export_ui';
  }
}

/**
 * Implementation of hook_theme().
 */
function context_ui_theme() {
  $items = array();
  $items['context_ui_form'] = array(
    'render element' => 'form',
    'path' => drupal_get_path('module', 'context_ui') .'/theme',
    'template' => 'context-ui-form',
    'file' => 'theme.inc',
  );
  $items['context_ui_plugins'] = array(
    'render element' => 'form',
    'path' => drupal_get_path('module', 'context_ui') .'/theme',
    'template' => 'context-ui-plugins',
    'file' => 'theme.inc',
  );
  $items['context_ui_editor'] = array(
    'render element' => 'form',
    'path' => drupal_get_path('module', 'context_ui') .'/theme',
    'template' => 'context-ui-editor',
    'file' => 'theme.inc',
  );
  return $items;
}

/**
 * Implementation of hook_block_info().
 */
function context_ui_block_info() {
  $blocks = array();
  $blocks['editor'] = array('info' => t('Context editor'), 'admin' => TRUE);
  if (module_exists('devel')) {
    $blocks['devel'] = array('info' => t('Context inspector'), 'admin' => TRUE);
  }
  return $blocks;
}

/**
 * Implementation of hook_block_view().
 */
function context_ui_block_view($delta = '') {
  switch ($delta) {
    case 'editor':
      if (user_access('administer contexts') && strpos($_GET['q'], 'admin/structure/context') === FALSE && $contexts = context_active_contexts()) {
        return array(
          'subject' => t('Context editor'),
          'content' => drupal_get_form('context_ui_editor', $contexts),
        );
      }
      break;
    case 'devel':
      if (module_exists('devel') && $all = context_get()) {
        return array(
          'subject' => t('Context inspector'),
          'content' => kdevel_print_object($all),
        );
      }
      break;
  }
}

/**
 * Implementation of hook_permission().
 */
function context_ui_permission() {
  $permissions = array();
  $permissions['administer contexts'] = array(
    'title' => 'Administer contexts',
    'description' => 'Associate menus, views, blocks, etc. with different contexts to structure your site.'
  );
  $permissions['context ajax block access'] = array(
    'title' => t('Access All Blocks'),
    'description' => t('Allows users to access all rendered blocks via an AJAX callback. If you have some blocks that should not be rendered for some users but need those users to be able to use context UI, then implement hook_context_allow_ajax_block_access with the necessary logic.'),
  );
  return $permissions;
}

/**
 * Implementation of hook_menu().
 */
function context_ui_menu() {
  $items = array();
  $items['admin/structure/context/settings'] = array(
    'title' => 'Settings',
    'access callback' => 'user_access',
    'access arguments' => array('administer contexts'),
    'page callback' => 'drupal_get_form',
    'page arguments' => array('context_ui_settings'),
    'type' => MENU_LOCAL_TASK,
    'weight' => 3,
  );
  $items['context-ui/activate'] = array(
    'title' => 'Activate Context UI',
    'access arguments' => array('administer contexts'),
    'page callback' => 'context_ui_activate',
    'type' => MENU_CALLBACK
  );
  $items['context-ui/deactivate'] = array(
    'title' => 'Deactivate Context UI',
    'access arguments' => array('administer contexts'),
    'page callback' => 'context_ui_deactivate',
    'type' => MENU_CALLBACK
  );
  return $items;
}

/**
 * Implementation of hook_help().
 */
function context_ui_help($path, $arg) {
  switch ($path) {
    case 'admin/help#context_ui':
      $output = file_get_contents(drupal_get_path('module', 'context_ui') .'/README.txt');
      return module_exists('markdown') ? filter_xss_admin(module_invoke('markdown', 'filter', 'process', 0, -1, $output)) : '<pre>'. check_plain($output) .'</pre>';
    case 'admin/structure/context':
      return '<p>'. t('Context allows you to manage contextual conditions and reactions for different portions of your site. You can think of each context as representing a "section" of your site. For each context, you can choose the conditions that trigger this context to be active and choose different aspects of Drupal that should react to this active context.') .'</p>';
  }
}

/**
 * Inline context editor form.
 */
function context_ui_editor($form, &$form_state, $contexts) {
  $form = array(
    '#attributes' => array('class' => array('context-editor')),
    '#theme' => array('context_ui_editor'),
    'editables' => array(),
    'contexts' => array('#tree' => TRUE),
    'buttons' => array('#tree' => FALSE),
  );

  $form['title'] = array(
    '#prefix' => '<h2 class="context-editor-title">',
    '#markup' => t('Select the Context/Layer to Edit'),
    '#suffix' => '</h2>',
    '#weight' => -2,
  );

  //add some help text to the top of the form
  $form['help'] = array (
    '#prefix' => '<p class="context-help help">',
    '#markup' => t('Select which context, or layer of blocks, to edit.
                    Each context is configured to appear on different sets of pages so read the description carefully.
                    When you are done editing click Done and save your changes.
                    You may use the Stop Editing Layout link to close the editor.'),
    '#suffix' => '</p>',
    '#weight' => -1,
  );

  $items = array();
  $form_context = array();
  ksort($contexts);
  foreach ($contexts as $context) {
    $edit = l(t('Edit'), $_GET['q'], array('fragment' => $context->name, 'attributes' => array('class' => array('edit'))));
    $done = l(t('Done'), $_GET['q'], array('fragment' => $context->name, 'attributes' => array('class' => array('done'))));
    $readable_name = ucwords(str_replace('_', ' ', $context->name));
    $description = empty($context->description) ? '' :
                        "<br/><div class='label bottom'>".check_plain($context->description)."</div>";
    $items[] = array(
      'data' => "<div class='label top'>" . $readable_name. "</div><div class='links'>{$edit} {$done}</div>" . $description,
      'class' => array('context-editable clearfix'),
      'id' => "context-editable-trigger-{$context->name}",
    );
    $form_context = array(
      '#tree' => TRUE,
      '#type' => module_exists('admin') ? 'admin_panes' : NULL,
      'context' => array('#type' => 'value', '#value' => $context),
    );

    // Edit context reactions.
    foreach (array_keys(context_reactions()) as $reaction) {
      $plugin = context_get_plugin('reaction', $reaction);
      if (method_exists($plugin, 'editor_form') && ($plugin_form = $plugin->editor_form($context))) {
        $form_context["reaction-{$reaction}"] = $plugin_form + array('#title' => $plugin->title);
      }
    }

    // Add to main form.
    $form['contexts'][$context->name] = $form_context;
  }

  // Display editable contexts in list.
  $form['editables']['#markup'] = theme('item_list', array('items' => $items));

  // Buttons.
  $form['buttons']['save'] = array(
    '#type' => 'submit',
    '#value' => t('Save changes'),
    '#submit' => array('context_ui_editor_submit'),
  );
  $form['buttons']['cancel'] = array(
    '#type' => 'submit',
    '#value' => t('Reset'),
    '#submit' => array('context_ui_editor_cancel'),
  );

  $form['stop'] = array(
    '#markup' => l(t('Stop Editing Layout'), 'context-ui/deactivate', array(
        'query' => array('destination' => current_path()),
        'attributes' => array('class' => array('context_ui_dialog-stop')),
      )
    ),
  );

  return $form;
}

/**
 * Values processor for context_ui_editor_submit().
 * Split out for reuse by overriding submit handlers.
 */
function context_ui_editor_process($values) {
  $context = $values['context'];
  foreach (array_keys(context_conditions()) as $condition) {
    if (isset($values['condition'][$condition])) {
      $plugin = context_get_plugin('condition', $condition);
      if ($plugin && method_exists($plugin, 'editor_form_submit')) {
        $context->conditions[$condition]['values'] = $plugin->editor_form_submit($context, $values['condition'][$condition]);
      }
    }
    if (isset($context->conditions[$condition]) && context_empty($context->conditions[$condition]['values'])) {
      unset($context->conditions[$condition]);
    }
  }
  foreach (array_keys(context_reactions()) as $reaction) {
    if (isset($values["reaction-{$reaction}"])) {
      $plugin = context_get_plugin('reaction', $reaction);
      if ($plugin && method_exists($plugin, 'editor_form_submit')) {
        $context->reactions[$reaction] = $plugin->editor_form_submit($context, $values["reaction-{$reaction}"]);
      }
    }
    if (isset($context->reactions[$reaction]) && context_empty($context->reactions[$reaction])) {
      unset($context->reactions[$reaction]);
    }
  }
  return $context;
}

/**
 * Save handler for context_block_editor().
 */
function context_ui_editor_submit(&$form, &$form_state) {
  foreach ($form_state['values']['contexts'] as $name => $values) {
    $original_reactions = var_export($values['context']->reactions, TRUE);
    $context = context_ui_editor_process($values);
    //compare string values instead of actual objects to avoid problems with aliasing
    if (($original_reactions !== var_export($context->reactions, TRUE))) {
      if (context_save($context)) {
        drupal_set_message(t('Saved %title.', array(
          '%title' => (!empty($context->description) ? $context->description : $context->name)
        )));
      }
      else {
        drupal_set_message(t('Could not save context %title.', array('%title' =>  $context->name)), 'error');
      }
    }
  }
  return;
}

/**
 * Cancel handler for context_block_editor().
 */
function context_ui_editor_cancel(&$form, &$form_state) {
  return;
}

/**
 * Settings form.
 */
function context_ui_settings($form, &$form_state) {
  $form = array();
  foreach (context_conditions() as $condition => $info) {
    if ($plugin = context_get_plugin('condition', $condition)) {
      $settings_form = $plugin->settings_form();
      if ($settings_form) {
        $form['conditions'][$condition] = $settings_form;
        $form['conditions'][$condition]['#tree'] = FALSE;
        $form['conditions'][$condition]['#type'] = 'fieldset';
        $form['conditions'][$condition]['#title'] = $info['title'];
      }
    }
  }
  foreach (context_reactions() as $reaction => $info) {
    if ($plugin = context_get_plugin('reaction', $reaction)) {
      $settings_form = $plugin->settings_form();
      if ($settings_form) {
        $form['reactions'][$reaction] = $settings_form;
        $form['reactions'][$reaction]['#tree'] = FALSE;
        $form['reactions'][$reaction]['#type'] = 'fieldset';
        $form['reactions'][$reaction]['#title'] = $info['title'];
      }
    }
  }
  $form['context_ui_dialog_enabled'] = array(
    '#type' => 'checkbox',
    '#title' => t('Use Context Editor Dialog'),
    '#default_value' => context_ui_dialog_is_enabled(),
    '#description' => t('When enabled all contextual links will have a Edit Layout link that will refresh the page with the context editor in a dialog box.'),
  );
  $form = system_settings_form($form);
  $form['#submit'][] = 'context_ui_settings_submit';
  return $form;
}

/**
 * Extra submit handler for context_ui_settings.
 * Mark the menu cache as needing a rebuild.
 */
function context_ui_settings_submit($form, &$form_state) {
  variable_set('menu_rebuild_needed', TRUE);
}


/**
 * context_ui_dialog_is_enabled test if the dialog is enabled
 */
function context_ui_dialog_is_enabled() {

  return variable_get("context_ui_dialog_enabled", FALSE);
}

/**
 * Implementation of hook_page_alter().
 *
 * If we have the dialog enabled and active build the dialog
 * and add to the page
 */
function context_ui_page_alter(&$page) {
  $contexts = context_active_contexts();
  if (
  context_ui_dialog_is_enabled()  &&
  context_isset('context_ui', 'context_ui_editor_present')
  ) {
    $contexts = context_active_contexts();
    $form = drupal_get_form('context_ui_editor', $contexts);

    $path = drupal_get_path('module', 'context_ui');
    drupal_add_library('system', 'ui.dialog');
    drupal_add_js($path . '/context_ui_dialog.js', array('type' => 'file', 'weight' => 50));
    drupal_add_css($path . '/context_ui_dialog.css');

    //figure out which region to put it in - allow it to be configured for themes using different regions
    $placement = variable_get('context_ui_editor_block_region', 'content');
    $page[$placement]['context_ui_editor'] = array(
      0 => array(
        '#type' => 'markup',
        '#markup' => '<div style="display:none;" id="context_ui_dialog-context-ui">' . drupal_render($form) . '<!--[if IE 8 ]><div id="context_ui_dialog-shadow"></div><![endif]--></div>',
      ),
    );
  }
}

/**
 * Implementation of hook_menu_contextual_links_alter().
 *
 * we we have the dialog enabled lets add a link to all contextual links
 * to activate it.
 */
function context_ui_menu_contextual_links_alter(&$links, $router_item, $root_path) {
  if(context_ui_dialog_is_enabled()  &&
     !context_isset('context_ui', 'context_ui_editor_present') && user_access('administer contexts')) {
    $links['layout'] = array(
      'href' => 'context-ui/activate',
      'title' => t('Configure Layout'),
      'localized_options' => array(
        'query' =>  array('destination'=> $_GET['q']),
        'options' => array('html' => FALSE, 'attributes' => array()),
      ),
    );
  }
}

/**
 * A page call back to activate the context_ui inline editor dialog.
 */
function context_ui_activate() {
  $_SESSION['context_ui_active'] = $_GET['destination'];
  drupal_goto($_GET['destination']);
}

/**
 * A page call back to deactivate the context_ui inline editor dialog.
 * This is semi unecessary as context editor will auto deactivate upon going to any
 * page other than the destination from the start. However, its useful as a place
 * to navigate to when deactivating context_ui_editor
 */
function context_ui_deactivate() {
  $_SESSION['context_ui_active'] = FALSE;
  drupal_goto($_GET['destination']);
}

/**
 * Implemenation of hook_init().
 *
 * If the session says we should have an active dialog set a context variable to tell everything else
 * Ignores ajax requests.
 */
function context_ui_init() {
  if (!empty($_SESSION['context_ui_active'])) {
    $path = $_SESSION['context_ui_active'];
    if( $path == request_path() || $path == drupal_get_path_alias() || $path == drupal_get_normal_path(request_path()) ) {
      context_set('context_ui', 'context_ui_editor_present', TRUE);
    }
  }
  // Turn off functionality has been moved to hook_page_build() to prevent non-pages from triggering it
}

/**
 *  Implementation of hook_page_build().
 *  Turn off the context_ui functionality if we move to a different page
 */
function context_ui_page_build(&$page) {
  if (!context_get('context_ui', 'context_ui_editor_present') && isset($_SESSION['context_ui_active'])) {
    $_SESSION['context_ui_active'] = FALSE;
  }
}

/**
 *  Ajax callback to get the list of available blocks
 *
 */
function context_ui_get_available_blocks() {
  drupal_json_output(array('lols' => 'testing'));
}
