<?php

/**
 * @file
 * Administrative interface for Skinr Context. Without this module, you cannot edit your skins with context.
 */

/**
 * Implements hook_menu().
 */
function skinr_context_ui_menu() {
  $items['admin/structure/skinr/edit/%/%/%skinr_context_group'] = array(
    'title' => 'Edit skin',
    'title callback' => 'skinr_context_ui_edit_title',
    'title arguments' => array(4, 5, 6),
    'page callback' => 'skinr_context_ui_edit',
    'page arguments' => array(4, 5, 6), // module, element, gid
    'type' => MENU_LOCAL_TASK,
    'access arguments' => array('edit skin settings'),
  );
  $items['admin/structure/skinr/edit/%/%/add'] = array(
    'title' => 'Add group',
    'page callback' => 'skinr_context_ui_group_add',
    'page arguments' => array(4, 5), // module, element
    'type' => MENU_LOCAL_ACTION,
    'access arguments' => array('edit skin settings'),
  );
  $items['admin/structure/skinr/edit/%/%/%skinr_context_group/delete'] = array(
    'title' => 'Delete group',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('skinr_context_ui_group_delete_confirm', 6),
    'type' => MENU_CALLBACK,
    'access arguments' => array('edit skin settings'),
  );

  return $items;
}

/**
 * Implements hook_menu_alter().
 */
function skinr_context_ui_menu_alter(&$items) {
  $items['admin/structure/skinr/edit/%/%']['page callback'] = 'skinr_context_ui_group_list';
  $items['admin/structure/skinr']['page arguments'] = array('skinr_context_ui_skin_list');
}

/**
 * Implements hook_menu_local_tasks_alter().
 */
function skinr_context_ui_menu_local_tasks_alter(&$data, $router_item, $root_path) {
  $destination = array();
  if (isset($_GET['destination'])) {
    $path = $_GET['q'];
    $query = drupal_http_build_query(drupal_get_query_parameters());
    if ($query != '') {
      $path .= '?' . $query;
    }
    $destination = array('destination' => $path);
  }

  if ($destination && $root_path == 'admin/structure/skinr/edit/%/%') {
    foreach ($data['actions']['output'] as $key => $item) {
      if ($item['#link']['path'] == 'admin/structure/skinr/edit/%/%/add') {
        // Add destination query string to link to preserve it.
        if (empty($data['actions']['output'][$key]['#link']['localized_options']['query'])) {
          $data['actions']['output'][$key]['#link']['localized_options']['query'] = array();
        }
        $data['actions']['output'][$key]['#link']['localized_options']['query'] += $destination;
      }
    }
  }
}

/**
 * Menu title callback; sets the title for a skins configuration form page.
 *
 * @param $module
 *   The module that we're editing settings of.
 * @param $element
 *   The element we're editing settings of.
 */
function skinr_context_ui_edit_title($module, $element, $group) {
  return t('Skin settings for !group group (!module type !element)', array('!group' => $group->title, '!module' => $module, '!element' => $element));
}

/**
 * Implements hook_theme().
 */
function skinr_context_ui_theme() {
  $items['skinr_context_ui_group_list_form'] = array(
    'render element' => 'form',
  );
  $items['skinr_context_ui_group_summary'] = array(
    'variables' => array('title' => NULL, 'description' => NULL),
  );
  return $items;
}

/**
 * Implements hook_help().
 */
function skinr_context_ui_help($path, $arg) {
  switch ($path) {
    case 'admin/structure/skinr/edit/%/%/%':
      // We're overriding paths in skinr_ui so make sure the proper help text
      // still appears.
      return skinr_ui_help('admin/structure/skinr/edit/%/%', $arg);
  }
}

/**
 * Menu callback; adds a skin settings group to an element.
 *
 * @param $module
 *   The module that we're adding a group to.
 * @param $element
 *   The element of the object we're adding a group to.
 */
function skinr_context_ui_group_add($module, $element) {
  return drupal_get_form('skinr_context_ui_group_add_form', $module, $element);
}

function skinr_context_ui_group_add_form($form, $form_state, $module, $element) {
  $form['module'] = array(
    '#type' => 'hidden',
    '#value' => $module,
  );
  $form['element'] = array(
    '#type' => 'hidden',
    '#value' => $element,
  );
  $form['title'] = array(
    '#type' => 'textfield',
    '#title' => t('Group title'),
    '#required' => TRUE,
    '#description' => t('Descriptive title for this skin settings group.'),
  );
  $form['description'] = array(
    '#type' => 'textfield',
    '#title' => t('Description'),
    '#description' => t('A description for this group.'),
  );

  $form['actions'] = array(
    '#tree' => FALSE,
    '#type' => 'actions',
  );
  $form['actions']['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Add group'),
  );

  return $form;
}

/**
 * Menu callback; allows adding a new skin settings group.
 */
function skinr_context_ui_group_add_form_submit($form, $form_state) {
  $group = (object) array(
    'gid' => NULL,
    'module' => $form_state['values']['module'],
    'element' => $form_state['values']['element'],
    'title' => $form_state['values']['title'],
    'description' => $form_state['values']['description'],
    'conditions' => array('sitewide' => array('values' => array(1 => 1))),
    'condition_mode' => CONTEXT_CONDITION_MODE_OR,
    'weight' => 0,
    'status' => 1,
  );
  skinr_context_group_save($group);
  drupal_goto('admin/structure/skinr/edit/' . $group->module . '/' . $group->element . '/' . $group->gid);
}

/**
 * Menu callback; lists skin settings groups for an element.
 *
 * @param $module
 *   The module that we're editing settings of.
 * @param $element
 *   The element of the object we're editing settings of.
 */
function skinr_context_ui_group_list($module, $element) {
  // Output list of groups.
  $gids = skinr_context_group_get_gids(array(
    'module' => $module,
    'element' => $element,
  ));
  $groups = skinr_context_group_load_multiple($gids);

  return drupal_get_form('skinr_context_ui_group_list_form', $groups);
}

/**
 * Form builder for the skin settings group listing.
 */
function skinr_context_ui_group_list_form($form, $form_state, $groups) {
  // Weights range from -delta to +delta, so delta should be at least half
  // of the amount of blocks present. This makes sure all blocks in the same
  // region get an unique weight.
  $weight_delta = round(count($groups) / 2);

  $form['groups'] = array();
  $form['#tree'] = TRUE;
  $form['#empty_text'] = t("You don't have any groups for this element.");

  foreach ($groups as $gid => $group) {
    $group = (array) $group;

    $form['groups'][$gid]['info'] = array(
      '#markup' => theme('skinr_context_ui_group_summary', array('title' => $group['title'], 'description' => $group['description'])),
    );
    $form['groups'][$gid]['status'] = array(
      '#type' => 'checkbox',
      '#default_value' => $group['status'],
      '#title_display' => 'invisible',
      '#title' => t('Enable @group group', array('@group' => $group['title'])),
    );
    $form['groups'][$gid]['weight'] = array(
      '#type' => 'weight',
      '#default_value' => $group['weight'],
      '#delta' => $weight_delta,
      '#title_display' => 'invisible',
      '#title' => t('Weight for @group group', array('@group' => $group['title'])),
    );

    $destination = array();
    if (isset($_GET['destination'])) {
      $path = $_GET['q'];
      $query = drupal_http_build_query(drupal_get_query_parameters());
      if ($query != '') {
        $path .= '?' . $query;
      }
      $destination = array('destination' => $path);
    }

    $operations = array();
    $operations['edit'] = array(
      '#type' => 'link',
      '#title' => t('edit'),
      '#href' => 'admin/structure/skinr/edit/' . $group['module'] . '/' . $group['element'] . '/' . $group['gid'],
      '#options' => array('query' => $destination),
    );
    $operations['delete'] = array(
      '#type' => 'link',
      '#title' => t('delete'),
      '#href' => 'admin/structure/skinr/edit/' . $group['module'] . '/' . $group['element'] . '/' . $group['gid'] . '/delete',
      '#options' => array('query' => $destination),
    );
    $form['groups'][$gid]['operations'] = $operations;
  }

  // Prepare cancel link.
  if (isset($_GET['destination'])) {
    $options = drupal_parse_url(urldecode($_GET['destination']));
  }
  else {
    $options = array('path' => 'admin/structure/skinr');
  }

  $form['actions'] = array(
    '#tree' => FALSE,
    '#type' => 'actions',
  );
  $form['actions']['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Save groups'),
  );
  $form['actions']['done'] = array(
    '#type' => 'link',
    '#title' => t('Done'),
    '#href' => $options['path'],
    '#options' => $options,
  );

  return $form;
}

/**
 * Form submission handler for skinr_context_ui_group_list_form().
 */
function skinr_context_ui_group_list_form_submit($form, $form_state) {
  foreach ($form_state['values']['groups'] as $gid => $data) {
    // Load an uncached version of the skin settings group object.
    $group = skinr_context_group_load_unchanged($gid);
    // Let's save some time in skinr_context_group_save() by setting $group->original here.
    $group->original = clone($group);

    // Update status and weight.
    $group->status = $data['status'];
    $group->weight = $data['weight'];
    skinr_context_group_save($group);
  }
}

/**
 * Returns HTML for the menu overview form into a table.
 *
 * @param $variables
 *   An associative array containing:
 *   - form: A render element representing the form.
 *
 * @ingroup themeable
 */
function theme_skinr_context_ui_group_list_form($variables) {
  $form = $variables['form'];

  drupal_add_tabledrag('skinr-context-ui-group-list', 'order', 'sibling', 'skinr-context-ui-group-weight');

  $header = array(
    t('Skin settings group'),
    array('data' => t('Enabled'), 'class' => array('checkbox')),
    t('Weight'),
    array('data' => t('Operations'), 'colspan' => '2'),
  );

  $rows = array();
  foreach (element_children($form['groups']) as $gid) {
    if (isset($form['groups'][$gid]['status'])) {
      $element = &$form['groups'][$gid];
      // Build a list of operations.
      $operations = array();
      foreach (element_children($element['operations']) as $op) {
        $operations[] = array('data' => drupal_render($element['operations'][$op]), 'class' => array('skinr-context-ui-group-operations'));
      }

      // Add special classes to be used for tabledrag.js.
      $element['weight']['#attributes']['class'] = array('skinr-context-ui-group-weight');

      $row = array();
      $row[] = drupal_render($element['info']);
      $row[] = array('data' => drupal_render($element['status']), 'class' => array('checkbox', 'skinr-context-ui-group-enabled'));
      $row[] = drupal_render($element['weight']);
      $row = array_merge($row, $operations);

      $row = array_merge(array('data' => $row), $element['#attributes']);
      $row['class'][] = 'draggable';
      $rows[] = $row;
    }
  }
  $output = '';
  if (empty($rows)) {
    $rows[] = array(array('data' => $form['#empty_text'], 'colspan' => '7'));
  }
  $output .= theme('table', array('header' => $header, 'rows' => $rows, 'attributes' => array('id' => 'skinr-context-ui-group-list')));
  $output .= drupal_render_children($form);
  return $output;
}

/**
 * Form builder for the skinr settings group delete confirmation form.
 *
 * @param $group
 *   Skinr settings group object.
 *
 * @ingroup forms
 */
function skinr_context_ui_group_delete_confirm($form, &$form_state, $group) {
  $form['#group'] = $group;
  $form['gid'] = array(
    '#type' => 'value',
    '#value' => $group->gid,
  );

  return confirm_form($form,
    t('Are you sure you want to delete this skin settings group?'),
    isset($_GET['destination']) ? $_GET['destination'] : 'admin/structure/skinr/edit/' . $group->module . '/' . $group->element,
    t('This action cannot be undone.<br />Module: %module<br />Element: %element<br />Group: %group', array('%module' => $group->module, '%element' => $group->element, '%group' => $group->title)),
    t('Delete'),
    t('Cancel')
  );
}

/**
 * Form submission handler for skinr_context_ui_group_delete_confirm().
 */
function skinr_context_ui_group_delete_confirm_submit($form, &$form_state) {
  if ($form_state['values']['confirm']) {
    skinr_context_group_delete($form_state['values']['gid']);
    watchdog('content', 'Deleted a skin settings group.');
    drupal_set_message(t('A skin settings group has been deleted.'));
  }

  $group = $form['#group'];
  $form_state['redirect'] = 'admin/structure/skinr/edit/' . $group->module . '/' . $group->element;
}

/**
 * Menu callback; prepares some variables and displays a Skinr edit form.
 *
 * @param $module
 *   The module that we're editing settings of.
 * @param $element
 *   The element of the object we're editing settings of.
 * @param $elements
 *   An array of $element when more than one is returned from the preprocess
 *   index handler. Used by the javascript UI to update all elements involved.
 */
function skinr_context_ui_edit($module, $element, $group) {
  // Set defaults.
  $defaults = array();
  $themes = list_themes();
  foreach ($themes as $theme) {
    if (!$theme->status) {
      continue;
    }

    $params = array(
      'theme' => $theme->name,
      'module' => $module,
      'element' => $element,
      'gid' => $group->gid,
    );
    // Don't nest the call to skinr_skin_get_sids() in skinr_skin_load_multiple().
    // If the prior functions returns no results, the second function will load
    // ALL skins.
    if ($sids = skinr_context_group_get_sids($params)) {
      $skins = skinr_skin_load_multiple($sids);
      foreach ($skins as $skin) {
        $defaults[$theme->name][$skin->skin] = $skin->options;
      }
    }
  }
  return drupal_get_form('skinr_ui_form', array('module' => $module, 'element' => $element, 'gid' => $group->gid), $defaults);
}

/**
 * Implements hook_form_FORM_ID_alter().
 */
function skinr_context_ui_form_ctools_export_ui_edit_item_form_alter(&$form, &$form_state) {
  if ($form['info']['tag']['#default_value'] == 'Skinr') {
    // Prevent changing of required elements. For some reason if we disable the
    // tag field directly it doesn't get submitted. So we make a disabled copy
    // for display.
    $form['info']['alt_tag'] = $form['info']['tag'];
    $form['info']['alt_tag']['#disabled'] = TRUE;
    // Add weight to description to ensure proper order.
    $form['info']['description']['#weight'] = 1;
    $form['info']['tag']['#type'] = 'hidden';

    unset($form['reactions']);
  }
}

/**
 * Implements hook_form_alter().
 */
function skinr_context_ui_form_alter(&$form, $form_state, $form_id) {
  // Fix for update script.
  if ($form_id == 'update_script_selection_form') {
    return;
  }

  // Ensure module and element values are set.
  if (empty($form['skinr']['module']['#value']) || empty($form['skinr']['element']['#value'])) {
    return;
  }

  // Check for access.
  if (!skinr_ui_access('edit skin settings')) {
    // Deny access.
    return;
  }

  $group = skinr_context_group_load($form_state['build_info']['args'][0]['gid']);
  $form['skinr']['gid'] = array(
    '#type' => 'hidden',
    '#value' => $group->gid,
  );
  $form['skinr_group'] = array(
    '#tree' => TRUE,
    '#type' => 'container',
    // Move group settings to top.
    '#weight' => -1,
  );
  $form['skinr_group']['title'] = array(
    '#type' => 'textfield',
    '#title' => t('Group title'),
    '#required' => TRUE,
    '#default_value' => $group->title,
    '#description' => t('Descriptive title for this skin settings group.'),
  );
  $form['skinr_group']['description'] = array(
    '#type' => 'textfield',
    '#title' => t('Description'),
    '#description' => t('A description for this group.'),
  );

  // Context form elements.
  $context = skinr_context_group_to_context($group);

  // Condition mode
  $form['condition_mode'] = array(
    '#type' => 'checkbox',
    '#default_value' => isset($context->condition_mode) ? $context->condition_mode : FALSE,
    '#title' => t('Require all conditions'),
    '#description' => t('If checked, all conditions must be met for this context to be active. Otherwise, the first condition that is met will activate this context.')
  );
  // Condition plugin forms
  $form['conditions'] = array(
    '#theme' => 'context_ui_plugins',
    '#title' => t('Conditions'),
    '#description' => t('Trigger the activation of this context'),
    '#tree' => TRUE,
    'selector' => array(
      '#type' => 'select',
      '#options' => array(0 => '<'. t('Add a condition') .'>'),
      '#default_value' => 0,
    ),
    'state' => array(
      '#attributes' => array('class' => array('context-plugins-state')),
      '#type' => 'hidden',
    ),
    'plugins' => array('#tree' => TRUE),
  );

  $conditions = array_keys(context_conditions());
  sort($conditions);
  foreach ($conditions as $condition) {
    if ($plugin = context_get_plugin('condition', $condition)) {
      $form['conditions']['plugins'][$condition] = array(
        '#tree' => TRUE,
        '#plugin' => $plugin,
        '#context_enabled' => isset($context->conditions[$condition]), // This flag is used at the theme layer.
        'values' => $plugin->condition_form($context),
        'options' => $plugin->options_form($context),
      );
      $form['conditions']['selector']['#options'][$condition] = $plugin->title;
    }
  }

  // Only add submit handler once.
  if (isset($form['#submit']) && in_array('skinr_ui_form_submit', $form['#submit'])) {
    foreach ($form['#submit'] as $key => $submit_handler) {
      if ($submit_handler == 'skinr_ui_form_submit') {
        $form['#submit'][$key] = 'skinr_context_ui_form_submit';
      }
    }
  }
}

/**
 * Form submission handler for skinr_context_form_alter().
 */
function skinr_context_ui_form_submit($form, &$form_state) {
  $current_theme = skinr_current_theme(TRUE);

  $module = $form_state['values']['module'];
  $element = $form_state['values']['element'];
  $gid = $form_state['values']['gid'];

  // Save group settings.
  // Load an uncached version of the skin settings group object.
  $group = skinr_context_group_load_unchanged($gid);
  // Let's save some time in skinr_context_group_save() by setting $group->original here.
  $group->original = clone($group);

  // Update status and weight.
  $group->title = $form_state['values']['skinr_group']['title'];
  $group->description = $form_state['values']['skinr_group']['description'];

  // Update context.
  if (!empty($form['conditions'])) {
    $enabled = explode(',', $form_state['values']['conditions']['state']);
    foreach ($form_state['values']['conditions']['plugins'] as $condition => $values) {
      if (in_array($condition, $enabled, TRUE) && ($plugin = context_get_plugin('condition', $condition))) {
        if (isset($values['values'])) {
          $group->conditions[$condition]['values'] = $plugin->condition_form_submit($values['values']);
        }
        if (isset($values['options'])) {
          $group->conditions[$condition]['options'] = $plugin->options_form_submit($values['options']);
        }
        if (context_empty($group->conditions[$condition]['values'])) {
          unset($group->conditions[$condition]);
        }
      }
      else {
        unset($group->conditions[$condition]);
      }
    }
  }

  // Save group.
  skinr_context_group_save($group);

  // Save skin settings.
  if (!empty($form_state['values']['skinr_settings'])) {
    foreach ($form_state['values']['skinr_settings'] as $theme_name => $theme) {
      // Process widgets.
      if (!empty($theme) && is_array($theme)) {
        foreach ($theme as $skin_name => $options) {
          if ($skin_name == '_additional' && !user_access('edit advanced skin settings')) {
            // This user doesn't have access to alter these options.
            continue;
          }

          // Ensure options is an array.
          if (!is_array($options)) {
            $options = $skin_name == '_additional' ? explode(' ', $options) : array($options);
          }
          // Sanitize options.
          $options = _skinr_array_strip_empty($options);

          // Find existing skin.
          $params = array(
            'theme' => $theme_name,
            'module' => $module,
            'element' => $element,
            'gid' => $gid,
            'skin' => $skin_name,
          );
          $sids = skinr_context_group_get_sids($params);

          unset($skin);
          if (!empty($sids)) {
            $sid = reset($sids);
            $skin = skinr_skin_load($sid);
          }

          if (empty($options)) {
            if (!empty($skin)) {
              // Delete this skin setting.
              skinr_skin_delete($skin->sid);
            }
            continue;
          }

          if (empty($skin)) {
            // It doesn't exist, so create a new skin.
            $skin = new stdClass();
            $skin->theme = $theme_name;
            $skin->module = $module;
            $skin->element = $element;
            $skin->gid = $gid;
            $skin->skin = $skin_name;
          }
          $skin->options = $options;
          $skin->status = 1;

          // Save skin.
          if (!skinr_skin_save($skin)) {
            drupal_set_message(t("Skinr settings for %skin weren't saved due to an error.", array('%skin' => $skin_name)), 'error');
          }
        }
      }
    }
  }
}

/**
 * Implements hook_skinr_ui_filters_alter().
 */
function skinr_context_ui_skinr_ui_filters_alter(&$filters) {
  $groups = skinr_context_group_load_multiple(FALSE);

  $options = array('[any]' => t('any'));
  foreach ($groups as $group) {
    $options[$group->gid] = t('@group [gid: !gid]', array('@group' => $group->title, '!gid' => $group->gid));
  }

  $filters['gid'] = array(
    'title' => t('group'),
    'options' => $options,
  );

  // Reorder filters.
  $skin = $filters['skin'];
  unset($filters['skin']);
  $filters['skin'] = $skin;

  $status = $filters['status'];
  unset($filters['status']);
  $filters['status'] = $status;
}

/**
 * Apply filters for skin configuration administration filters based on session.
 *
 * @param $query
 *   A SelectQuery to which the filters should be applied.
 */
function skinr_context_ui_build_filter_query(SelectQueryInterface $query) {
  // Build query
  $filter_data = isset($_SESSION['skinr_ui_overview_filter']) ? $_SESSION['skinr_ui_overview_filter'] : array();
  foreach ($filter_data as $index => $filter) {
    list($key, $value) = $filter;
    if ($key == 'gid') {
      // Make exception for gid, which is in a different table.
      $query->condition('gs.' . $key, $value);
    }
    else {
      $query->condition('s.' . $key, $value);
    }
  }
}

/**
 * Overrides skinr_ui_list().
 *
 * @see skinr_ui_list()
 */
function skinr_context_ui_skin_list($form, &$form_state) {
  if (isset($form_state['values']['operation']) && $form_state['values']['operation'] == 'delete') {
    return skinr_ui_multiple_delete_confirm($form, $form_state, array_filter($form_state['values']['skins']));
  }
  $form['filter'] = skinr_ui_filter_form();
  $form['#submit'][] = 'skinr_ui_filter_form_submit';
  $form['admin'] = skinr_context_ui_skin_list_subform();

  return $form;
}

/**
 * Overrides skinr_ui_admin_skins().
 *
 * @see skinr_ui_admin_skins()
 */
function skinr_context_ui_skin_list_subform() {
  // Build the 'Update options' form.
  $form['options'] = array(
    '#type' => 'fieldset',
    '#title' => t('Update options'),
    '#attributes' => array('class' => array('container-inline')),
  );
  $options = array();
  foreach (module_invoke_all('skinr_ui_operations') as $operation => $array) {
    $options[$operation] = $array['label'];
  }
  $form['options']['operation'] = array(
    '#type' => 'select',
    '#title' => t('Operation'),
    '#title_display' => 'invisible',
    '#options' => $options,
    '#default_value' => 'enable',
  );
  $form['options']['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Update'),
    '#validate' => array('skinr_ui_admin_skins_validate'),
    '#submit' => array('skinr_ui_admin_skins_submit'),
  );

  $header = array(
    'theme' => array('data' => t('Theme'), 'field' => 's.theme'),
    'type' => array('data' => t('Type'), 'field' => 's.module'),
    'group' => array('data' => t('Group'), 'field' => 'gs.gid'),
    'element' => array('data' => t('Element'), 'field' => 's.element'),
    'skin' => array('data' => t('Skin'), 'field' => 's.skin'),
    'status' => array('data' => t('Status'), 'field' => 's.status'),
    'operations' => array('data' => t('Operations')),
  );

  $query = db_select('skinr_skins', 's')->extend('PagerDefault')->extend('TableSort');
  $query->join('skinr_group_skins', 'gs', 's.sid = gs.sid');
  skinr_context_ui_build_filter_query($query);

  $sids = $query
    ->fields('s', array('sid'))
    ->limit(50)
    ->orderByHeader($header)
    ->execute()
    ->fetchCol();
  $skins = skinr_skin_load_multiple($sids);

  $themes = list_themes();
  $skin_info = skinr_get_skin_info();
  $destination = drupal_get_destination();
  $options = array();
  foreach ($skins as $skin) {
    $operations = array(
      'edit' => array(
        'title' => t('edit'),
        'href' => 'admin/structure/skinr/edit/' . $skin->module . '/' . $skin->element . '/' . $skin->gid,
        'query' => $destination,
      ),
      'status' => array(
        'title' => $skin->status ? t('disable') : t('enable'),
        'href' => 'admin/structure/skinr/skin/' . $skin->sid . '/' . ($skin->status ? 'disable' : 'enable'),
        'query' => $destination + array(
          'token' => drupal_get_token('admin/structure/skinr/skin/' . $skin->sid . '/' . ($skin->status ? 'disable' : 'enable')),
        ),
      ),
      'delete' => array(
        'title' => t('delete'),
        'href' => 'admin/structure/skinr/skin/' . $skin->sid . '/delete',
        'query' => $destination,
      ),
    );

    $group = skinr_context_group_load($skin->gid);
    $title = reset(skinr_invoke_all('skinr_ui_element_title', $skin->module, $skin->element, $skin->theme));
    $options[$skin->sid] = array(
      'theme' => isset($themes[$skin->theme]) ? $themes[$skin->theme]->info['name'] : '<em>' . $skin->theme . '</em>',
      'type' => $skin->module,
      'group' => t('@group [gid: !gid]', array('@group' => $group->title, '!gid' => $group->gid)),
      'element' => $title ? $title : $skin->element,
      'skin' => $skin->skin == '_additional' ? '<em>' . t('Additional classes') . '</em>' : (isset($skin_info[$skin->skin]) ? $skin_info[$skin->skin]['title'] : '<em>' . $skin->skin . '</em>'),
      'status' => $skin->status ? t('enabled') : t('disabled'),
      'operations' => array(
        'data' => array(
          '#theme' => 'links__skinr_ui_operations',
          '#links' => $operations,
          '#attributes' => array('class' => array('links', 'inline')),
        ),
      ),
    );
  }

  $form['skins'] = array(
    '#type' => 'tableselect',
    '#header' => $header,
    '#options' => $options,
    '#empty' => t('No content available.'),
  );

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

/**
 * Returns HTML for title and descrition info for the skin settings groups listing.
 *
 * @param $variables
 *   An associative array containing:
 *   - title: The group's title.
 *   - description: The group's description.
 *
 * @ingroup themeable
 */
function theme_skinr_context_ui_group_summary($variables) {
  $info = '<strong class="title">' . $variables['title'] . '</strong>';
  if (!empty($variables['description'])) {
    $info .= '<div class="description">' . $variables['description'] . '</div>';
  }
  return '<div class="skin-group-summary">' . $info . '</div>';
}
