<?php
// $Id$

/**
 *  Implementation of hook_mapi_admin()
 */
function mapi_profile_mapi_admin($op, $data) {
  switch ($op) {
    case 'menu':
      if (!$data) {
        /*
        $items[] = array(
          'path' => MAPI_ADMIN_PATH ."/profiles",
          'title' => t('Profiles'),
          'description' => t('Profiles are the backbone to consistant presentation.'),
          'callback arguments' => array("mapi_profile_admin_form"),
        );
        $items[] = array(
          'path' => MAPI_ADMIN_PATH ."/profiles/add",
          'title' => t('Add Profile'),
          'callback arguments' => array("mapi_profile_admin_profile_form", null),
        );
        */
      }
      else {
      /*
        // deal with context information
        foreach (mapi_profile_defined() as $name) {
          $items[] = array(
            'path' => MAPI_ADMIN_PATH .'/profiles/'. $name,
            'title' => $name,
            'callback arguments' => array("mapi_profile_admin_profile_form", $name),
          );
        }
      */
      }
      return $items;
  }
}

/**
 *  Simply a list of the current profiles that exist.
 */
function mapi_profile_admin_form() {
  $form['header'] = array(
    '#prefix' => '<div>',
    '#value' => t('Profiles allow an administrator to provide a consistant presentation, providing preset settings for presenters.'),
    '#suffix' => '</div>'
  );

  $rows = array();
  foreach (mapi_profile_list() as $name) {
    if (mapi_profile_exists($name)) {
      $rows[] = array(
        l($name, MAPI_ADMIN_PATH .'/profiles/'. $name)
      );
    }
  }

  if (count($rows)) {
    $form['profiles'] = array('#value' => theme('table', array(), $rows));
  }
  else {
    $form['profiles'] = array('#value' => t('No profiles defined. Click !here to add a profile.', array('!here' => l(t('here'), MAPI_ADMIN_PATH .'/profiles/add'))));
  }

  return $form;
}

/**
 *  Allows for editing of the profile.
 */
function mapi_profile_admin_profile_form($name) {
  // check we have a valid profile to edit, or creating something
  if (!is_null($name) && !in_array($name, mapi_context_list())) {
    drupal_not_found();
    exit();
  }

  // load profile
  $profile = mapi_profile_load($name);

  // only show the profile if the context already known
  if (empty($profile)) {
    $form['context'] = array(
      '#type' => 'select',
      '#title' => t('Context'),
      '#description' => t('Select which context this profile will apply to.'),
      '#options' => drupal_map_assoc(mapi_profile_free()),
    );
  }
  else {
    $form['context'] = array('#type' => 'value', '#value' => $profile['context']);
    unset($profile['context']);
  }

  // cycle through all the variants of the presenters, creating the appropriate
  // details for them.
  // now the presenters
  $form['presenters'] = array('#tree' => true);

  foreach ($profile as $key => $object) {
    if (!is_numeric($key)) {
      continue;
    }

    $exts = $object->exts;

    $list = array();
    if (module_exists('mapi_derivatives')) {
      $list = mapi_derivative_list();

      foreach ($exts as $ext) {
        $new = mapi_derivatives_by_ext($ext);
        $list = array_intersect($list, $new);
      }
    }

    $item = array(
      '#type' => 'fieldset',
      '#title' => $object->presenter .' - '. implode(', ', $exts),
      '#collapsible' => true,
      '#collapsed' => true,
      // buttons for changing details
      '_delete'    => (count($profile) > 1 ?
        array('#type' => 'submit', '#value' => 'delete-'. $key, '#attributes' => array('class' => 'mapi-profile-delete')) :
        null
      ),
      '_update'    => array('#type' => 'submit', '#value' => t('Update'), '#attributes' => array('class' => 'mapi-profile-update')),

      // save and present the settings for this presenter
      'exts'       => array('#type' => 'value', '#value' => $exts),
      'presenter'  => array('#type' => 'value', '#value' => $object->presenter),
      'derivative' => (count($list) ?
        array('#type' => 'select', '#title' => t('Derivative'), '#options' => drupal_map_assoc(array_merge(array('original'), $list)), '#default_value' => $object->derivative) :
        array('#type' => 'textfield', '#title' => t('File'), '#value' => 'original', '#disabled' => true)
      ),
      'settings'  => mapi_presenter_form($object->presenter, $object->settings)
    );

    $form['presenters'][$key] = $item;
  }

  $list = array('original');
  $list = array_merge($list, (module_exists('mapi_derivatives') ? mapi_derivative_list() : array()));

  $form['new'] = array(
    '#tree' => true,
    '#type' => 'fieldset',
    '#title' => t('New Presenter Style'),
    'exts' => array(
      '#type' => 'checkboxes',
      '#title' => t('Extensions'),
      '#options' => drupal_map_assoc(mapi_profile_free_extensions($name)),
    ),
    'presenter' => array(
      '#type' => 'select',
      '#title' => t('Presenter'),
      '#options' => drupal_map_assoc(array_merge(array('generic'), mapi_presenter_list())),
    ),
    'derivative' => (count($list) ?
      array('#type' => 'select', '#title' => t('Derivative'), '#options' => drupal_map_assoc($list)) :
      array('#type' => 'textfield', '#title' => t('File'), '#value' => 'original', '#disabled' => true)
    ),
    'add' => array('#type' => 'submit', '#value' => t('Add'))
  );

  $form['disclaimer'] = array(
    '#value' => '<div>'. t('Extensions left unused in the profiles use the defaults settings for that extension.') .'</div>',
  );

  return $form;
}

function mapi_profile_admin_profile_form_validate($form_id, $form_values) {
  if ($form_values['op'] == t('Add')) {
    $details = $form_values['new'];
    $exts = array_filter($details['exts']);

    $diff_ext = array_diff($exts, mapi_presenter_extensions($details['presenter']));

    // check that extensions selected match the presenter
    if (count($diff_ext)) {
      form_set_error('exts', t('Selected presenter cannot handle the following extensions: !ext', array('!ext' => implode(', ', $diff_ext))));
      return;
    }

    // check that the extensions match the derivative
    if ($details['derivative'] != 'original') {
      foreach ($exts as $ext) {
        if (!in_array($details['derivative'], mapi_derivatives_by_ext($ext))) {
          form_set_error('derivative', t('The derivative selected does not function with extension %ext', array('%ext' => $ext)));
          return;
        }
      }
    }
  }
}

function mapi_profile_admin_profile_form_submit($form_id, $form_values) {
  switch ($form_values['op']) {
    case t('Update'):
      mapi_profile_update($form_values['context'], $form_values['presenters']);
      break;
    case t('Add'):
      $details = $form_values['new'];

      // creates a new blank profile for the name
      if (count($form_values['presenters'])) {
        $details = $form_values['new'];

        // add details to the presenters
        $profile = $form_values['presenters'];
        $profile[0] = array(
          'exts' => array_filter($details['exts']),
          'presenter' => $details['presenter'],
          'derivative' => $details['derivative'],
          'settings' => array(),
        );
        // update the profile
        mapi_profile_update($form_values['context'], $profile);
      }
      else {
        $details = $form_values['new'];
        if ($profile = mapi_profile_create($form_values['context'], array_filter($details['exts']), $details['presenter'], $details['derivative'], array())) {
          return MAPI_ADMIN_PATH .'/profiles/'. $form_values['context'];
        }
      }
      break;
    default:
      $ops = explode('-', $form_values['op']);
      if (count($ops) == 2 && ($ops[0] == 'delete')) {
        if (isset($form_values['presenters'][$ops[1]])) {
          unset($form_values['presenters'][$ops[1]]);
          mapi_profile_update($form_values['context'], $form_values['presenters']);
        }
      }
      break;
  }
}

function mapi_profile_admin_context_form($context) {
  if (!is_null($context)) {
    drupal_not_found();
    exit();
  }

  $form['context'] = array(
    '#type' => 'textfield',
    '#title' => t('Name'),
    '#description' => t('Name of the description, use only alphanumerics and hyphen.'),
  );

  $form['create'] = array(
    '#type' => 'submit',
    '#value' => t('Submit'),
  );

  return $form;
}

function mapi_profile_admin_context_form_validate($form_id, $form_values) {
  if ($form_values['op'] == t('Delete')) {
    drupal_goto(MAPI_ADMIN_PATH .'/contexts/'. $form_values['context'] .'/delete');
    exit();
  }
  if (preg_match('/[^\w\-]/', $form_values['context'])) {
    form_set_error('context', t('Name must only contain alphanumeric or hyphen characters.'));
  }
  if ($form_values['op'] == t('Submit')) {
    if (in_array($form_values['context'], mapi_context_list())) {
      form_set_error('context', t('Context with that name already exists.'));
    }
  }
}

function mapi_profile_admin_context_form_submit($form_id, $form_values) {
  if ($form_values['op'] == t('Submit')) {
    if (!in_array($form_values['context'], mapi_profile_user())) {
      $cid = db_next_id("{mapi_contexts}_cid");
      db_query("INSERT INTO {mapi_contexts} (cid, name) VALUES (%d, '%s')", $cid, $form_values['context']);
    }
  }
  return MAPI_ADMIN_PATH .'/contexts';
}

function mapi_profile_admin_context_delete_form($context) {
  // load the media item
  if (!in_array($context, mapi_profile_user())) {
    drupal_not_found();
    exit();
  }

  // remember for confirmation of the media
  $form['context'] = array('#type' => 'value', '#value' => $context);

  // provide user interaction
  $notice = t('This action cannot be undone.');

  $form = confirm_form($form,
    t('Are you sure you want to delete context %title?', array('%title' => $context)),
    isset($_GET['destination']) ? $_GET['destination'] : MAPI_ADMIN_PATH ."/contexts",
    $notice,
    t('Delete'), t('Cancel'));

  return $form;
}

function mapi_profile_admin_context_delete_form_submit($form_id, $form_values) {
  if ($form_values['confirm'] == 1) {
    db_query("DELETE FROM {mapi_contexts} WHERE name='%s'", $form_values['context']);
  }

  return (isset($_GET['destination']) ? $_GET['destination'] : MAPI_ADMIN_PATH ."/contexts");
}
