<?php
// $Id$

/**
 * Administration Settings Form
 *
 * This contains the following:
 * - Paths (public, private, temp)
 * - File structure settings
 * - Node defaults
 *
 */
function mapi_admin_settings_form() {
  drupal_set_title(t('Media Settings'));

  $form = mapi_admin_invoke('settings');

  if (!count($form)) {
    $form[] = array('#value' => t('Currently no settings are supplied for the mapi administration'));
  }

  return system_settings_form($form);
}

/**
 * Administration Extensions Form
 *
 * This contains the following:
 * - Default Presenter for an Extension
 *
 */
function mapi_admin_extensions_form($ext) {
  $exts = mapi_extension_list();
  // specific to the extension which we're selecting
  if (in_array($ext, $exts)) {
    drupal_set_title(t('Media Extension %ext', array('%ext' => $ext)));

    // create presenter list
    $plist = array();
    $plist[false] = t('none');
    foreach (mapi_presenter_by_ext($ext) as $presenter) {
      $plist[$presenter] = $presenter;
    }

    $form['header'] = array('#value' => t('Please choose the default presenter for each extension type.') .'<p />');

    // select presenter for the extension
    $form["mapi_ext_{$ext}_presenter"] = array(
      '#type' => 'select',
      '#title' => $ext,
      '#options' => $plist,
      '#default_value' => mapi_presenter_default($ext),
    );

    $form['footer'] = array(
      '#prefix' => '<div>',
      '#value' => l(t('presenters'), MAPI_ADMIN_PATH .'/presenters') .' | '. l(t('extensions'), MAPI_ADMIN_PATH .'/extensions'),
      '#suffix' => '</div><p />',
    );

    $form = system_settings_form($form);
  }
  else {
    drupal_set_title(t('Media Extensions'));

    $form['header'] = array('#value' => t('The list of extensions with default presenter and derivative.') .'<p />');

    $rows = array();
    // Theme the presenters in a way that allows it to handle multiple levels
    foreach ($exts as $ext) {
      $default = mapi_presenter_default($ext);
      $row = array(l($ext, MAPI_ADMIN_PATH .'/extensions/'. $ext), ($default ? $default : t('none')));
      $rows[] = $row;
    }

    $form['table'] = array('#value' => theme('table', array(t('Extensions'), t('Default Presenter')), $rows));
  }

  return $form;
}

/**
 * Administration Types General Form
 *
 * This contains the list of the current available types.
 * Otherwise if a type is selected, then we use the Type Information form
 *
 */
function mapi_admin_types_form($type) {
  // List all the types, and the extensions that exist, as well as the
  // presenter for each of the types. Provide links to all of them.
  if ($type && in_array($type, mapi_type_list())) {
    return mapi_admin_types_info_form($type);
  }

  drupal_set_title(t('Media Types'));

  $types = mapi_type_list();

  $form['header'] = array('#value' => t('These are the types which are associated with each of the different extensions.') .'<p />');

  $rows = array();
  foreach ($types as $type) {
    $details = mapi_type_info($type);
    $rows[] = array($details['name'], $details['title'], $details['description'], l(t('extensions'), MAPI_ADMIN_PATH .'/types/'. $type));
  }
  $form['table'] = array('#value' => theme('table', array(t('Name'), t('Title'), t('Description'), ''), $rows));

  return $form;
}

/**
 * Administration Programs Form
 *
 */
function mapi_admin_programs_form($prog_id) {

  // The main programs so far will be imagemagick and ffmpeg. These are
  // for transformations which occur. Mostly it's to store the program
  // path, so that other programs can cleanly call the programs without
  // problems with security holes.

  $programs = mapi_program_list();

  // accessing particular program settings
  if (in_array($prog_id, $programs)) {

    $details = mapi_program_load($prog_id);

    $path = $details->path;

    $form['program'] = array('#type' => 'value', '#value' => $prog_id);

    $form['header'] = array('#prefix' => '<div>', '#value' => t('Change the settings for the program.'), '#suffix' => '</div>');
    $form['path'] = array(
      '#type' => 'textfield',
      '#title' => t('Path'),
      '#description' => t('Please provide the full path to the program.'),
      '#default_value' => $path,
    );
    $form['settings'] = mapi_invoke_programs('configure', $prog_id, unserialize($details->settings));
    $form['settings']['#tree'] = true;

    $form['submit'] = array('#type' => 'submit', '#value' => t('Submit'));
  }
  // otherwise, we list all the programs that exist
  else {
    $rows = array();
    if (count($programs) > 0) {
      foreach ($programs as $name) {
        $rows[] = array(l($name, MAPI_ADMIN_PATH .'/programs/'. $name));
      }
    }
    // no programs specified
    else {
      $rows[] = array(t('There are no programs installed.'));
    }

    $form['header'] = array('#value' => t('Settings for programs which can be used by transforms, or other modules.'));
    $form['table'] = array('#value' => theme('table', array(t('Programs')), $rows));
  }

  return $form;
}

/**
 *  Validate function for mapi_admin_programs_form
 */
function mapi_admin_programs_form_validate($form_id, $form_values) {
  if (!is_file($form_values['path'])) {
    form_set_error('path', t('There is no file located at the specified path.'));
    return;
  }
  mapi_invoke_programs('validate', $program, $form_values['settings']);
}

/**
 *  Submit function for mapi_admin_programs_form
 */
function mapi_admin_programs_form_submit($form_id, $form_values) {
  $settings = mapi_invoke_programs('save', $program, $form_values['settings']);
  $settings = (isset($settings) ? $settings : $form_values['settings']);

  mapi_program_update($form_values['program'], $form_values['path'], $form_values['settings']);
}


/**
 * Administration Presenters Information Form
 *
 * This contains the following:
 * - A list of the supported extensions.
 *
 */
function mapi_admin_presenters_form() {
  // List of the presenters, and the default settings for them all.
  // These are possible to change. Gives admin a little bit of control
  // over how these look as defaults.
  drupal_set_title(t('Media Presenters'));

  $form['header'] = array('#value' => t('The listing of all the extensions handled by the presenters.'));

  $form['presenter'] = array();
  $presenters = mapi_presenter_list();
  foreach ($presenters as $presenter) {
    $exts = mapi_presenter_extensions($presenter);
    foreach ($exts as $ext) {
      $form['presenter'][$presenter][$ext]['ext'] = array('#value' => l($ext, MAPI_ADMIN_PATH .'/extensions/'. $ext));
      $form['presenter'][$presenter][$ext]['default'] = array('#value' => (mapi_presenter_default($ext) === $presenter ? t('yes') : ''));
    }
  }

  return $form;
}

/**
 * Administration Types Information Form
 *
 * This contains the following:
 * - A list of the supported extensions.
 *
 */
function mapi_admin_types_info_form($type) {
  drupal_set_title(t('Media type %type', array('%type' => $type)));

  $form['header'] = array('#value' => t('Settings for the node type %type.', array('%type' => $type)) .'<p />');

  $exts = array();
  if ($type == 'generic') {
    $list = mapi_extension_list();
  }
  else {
    $list = mapi_type_extensions($type);
  }
  foreach ($list as $ext) {
    $exts[] = l($ext, MAPI_ADMIN_PATH .'/extensions/'. $ext);
  }

  $form['exts'] = array('#value' => theme('item_list', $exts, t('Extensions')));

  return $form;
}

/**
 *  Administration Profiles Form
 */
function mapi_admin_profiles_form($profile) {
  if (!is_null($profile) && !in_array($profile, mapi_profile_list())) {
    drupal_not_found();
    exit();
  }

  // handle the profile details
  if ($profile) {
    // currently this does nothing except allow it to be deleted.
    $profile = mapi_profile_load($profile);

    $handlers = mapi_invoke_profile('list', $profile, null);
    if (array_key_exists($profile->name, $handlers)) {
      $handlers = $handlers[$profile->name];
      $list = variable_get('mapi_profile_handlers', array());
      $form['handler'] = array(
        '#type' => 'select',
        '#title' => t('Handler'),
        '#default_value' => (array_key_exists($profile->name, $list) ? $list[$profile->name] : array_shift(array_values($handlers))),
        '#options' => drupal_map_assoc($handlers),
        '#description' => t('This selects which module handles processing of this profile.'),
      );
    }

    $form['#profile'] = $profile;
    $form['profile'] = array('#type' => 'value', '#value' => $profile->name);
    $form['submit'] = array('#type' => 'submit', '#value' => t('Submit'), '#weight' => 50);
    $form['delete'] = array('#type' => 'submit', '#value' => t('Delete'), '#weight' => 50);
  }
  // handle the profile listing
  else {
    $rows = array();
    foreach (mapi_profile_list() as $profile) {
      $rows[] = array(l($profile, MAPI_ADMIN_PATH .'/profiles/'. $profile));
    }
    if (!count($rows)) {
      $rows[] = array(t('No profiles are currently defined.'));
    }
    $form[] = array('#value' => theme('table', array(), $rows));
  }

  return $form;
}

function mapi_admin_profiles_form_submit($form_id, $form_values) {
  if ($form_values['op'] == t('Delete')) {
    return MAPI_ADMIN_PATH .'/profiles/'. $form_values['profile'] .'/delete';
  }

  if ($form_values['op'] == t('Submit')) {
    if (isset($form_values['handler'])) {
      $handlers = variable_get('mapi_profile_handlers', array());
      $handlers[$form_values['profile']] = $form_values['handler'];
      variable_set('mapi_profile_handlers', $handlers);
    }
  }

}

/**
 *  Administration Profiles Addition Form
 */
function mapi_admin_profiles_add_form() {
  $form['profile'] = 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_admin_profiles_add_form_validate($form_id, $form_values) {
  if (preg_match('/[^\w\-]/', $form_values['profile'])) {
    form_set_error('profile', t('Name must only contain alphanumeric or hyphen characters.'));
  }
  if ($form_values['op'] == t('Submit')) {
    if (in_array($form_values['profile'], mapi_profile_list())) {
      form_set_error('profile', t('Context with that name already exists.'));
    }
  }
}

function mapi_admin_profiles_add_form_submit($form_id, $form_values) {
  if ($form_values['op'] == t('Submit')) {
    if ($profile = mapi_profile_create($form_values['profile'])) {
      return MAPI_ADMIN_PATH .'/profiles/'. $profile->name;
    }
  }
  return MAPI_ADMIN_PATH .'/profiles';
}

function mapi_admin_profiles_delete_form($profile) {
  // load the media item
  if (!in_array($profile, mapi_profile_list())) {
    drupal_not_found();
    exit();
  }

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

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

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

  return $form;
}

function mapi_admin_profiles_delete_form_submit($form_id, $form_values) {
  if ($form_values['op'] == t('Delete')) {
    mapi_profile_delete($form_values['profile']);
  }

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



/**
 *  Themeing for the Admin Presenters Form
 */
function theme_mapi_admin_presenters_form(&$form) {
  $output = '';
  $output .= '<div>'. drupal_render($form['header']) .'</div>';

  $rows = array();
  if (is_array($form['presenter'])) {
    foreach (array_keys($form['presenter']) as $presenter) {
      if ($presenter{0} != '#') {
        $row = array();
        foreach (array_keys($form['presenter'][$presenter]) as $ext) {
          if ($ext{0} != '#') {
            $r = array();
            foreach (element_children($form['presenter'][$presenter][$ext]) as $key) {
              $r[] = drupal_render($form['presenter'][$presenter][$ext][$key]);
            }
            $row[] = $r;
          }
        }

        if (count($row)) {
          // add presenter name
          array_unshift($row[0], array( 'data' => $presenter, 'rowspan' => count($row)));
          $rows = array_merge($rows, $row);
        }
      }
    }
  }
  else {
    $rows = array(array(array('data' =>t('No presenters are installed'), 'colspan' => 3)));
  }

  $headers = array(
    t('Presenter'),
    t('Extension'),
    t('Default'),
  );

  $table = theme('table', $headers, $rows);

  $output .= '<div>'. $table .'</div>';
  $output .= drupal_render($form);

  return $output;
}
