<?php
// $Id$

/**
 *  Implementation of hook_form_alter()
 */
function mapi_profile_form_alter($form_id, &$form) {
  if ($form_id == 'mapi_admin_profiles_form') {
    if (isset($form['#profile'])) {
      // load the appropriate profile information
      require_once(drupal_get_path('module', 'mapi_profile') .'/admin.inc');

      // set the profile
      $profile = $form['#profile'];

      // add something to the form for processing.
      // process the different presenters.

      $form['mapi_profiles'] = array(
        '#type' => 'fieldset',
        '#title' => t('MAPI Profiles Settings'),
        '#tree' => true,
        '#collapsible' => true,
      );

      $items = array_merge($profile->settings, array('add' => 'add'));
      foreach ($items as $sid => $object) {
        $presenters = mapi_presenter_list();
        $presenters = array_merge(array('generic'), $presenters);

        $derivatives = mapi_derivative_list();
        $derivatives = array_merge(array('original'), $derivatives);

        $form['mapi_profiles'][$sid] = array(
          '#type' => 'fieldset',
          '#title' => (is_numeric($sid) ? t('Edit Settings') : t('Add Settings')),
          '#tree' => true,
          '#collapsible' => true,
          '#collapsed' => true
        );
        $form['mapi_profiles'][$sid]['presenter'] = array(
          '#type' => 'select',
          '#title' => t('Presenter'),
          '#options' => drupal_map_assoc($presenters),
          '#default_value' => $object->presenter,
        );
        $form['mapi_profiles'][$sid]['exts'] = array(
          '#type' => 'checkboxes',
          '#title' => t('Extensions'),
          '#options' => drupal_map_assoc(mapi_extension_list()),
          '#default_value' => $object->exts,
        );
        if (module_exists('mapi_derivatives')) {
          // skip the add object error
          if (is_object($object)) {
            $object->derivative = (!$object->derivative ? 'original' : $object->derivative);
          }
          $form['mapi_profiles'][$sid]['derivative'] = array(
            '#type' => 'select',
            '#title' => t('Derivative'),
            '#options' => drupal_map_assoc($derivatives),
            '#default_value' => (is_object($object) ? $object->derivative : 'original'),
            '#description' => t('Determines the derivative to be used for the appropriate extension.'),
          );
        }
        else {
          $form['mapi_profiles'][$sid]['derivative'] = array('#type' => 'value', '#value' => '');
        }
        $form['mapi_profiles']['add']['#collapsed'] = false;
        $form['mapi_profiles']['add']['submit'] = array('#type' => 'submit', '#value' => t('Add'));
      }

      $form['#validate']['_mapi_profile_form_validate'] = array();
      $form['#submit']['_mapi_profile_form_submit'] = array();
    }
  }
}

/**
 *  Implementation of hook_mapi_profile()
 */
function mapi_profile_mapi_profile($op, &$profile, $filename) {
  switch ($op) {

    case 'create':
      // don't create the profile settings, except when there are things to save.
      break;

    case 'delete':
      // delete profile settings
      if ($profile->name) {
        db_query("DELETE FROM {mapi_profile_settings} WHERE profile = '%s'", $profile->name);
      }
      break;

    case 'update':
      if ($profile->name && $profile->settings) {
        foreach ($profile->settings as $key => $object) {
          // check which to update (with double check of profile name, in case some module decideds to overwrite it)
          $object = db_fetch_object(db_query("SELECT sid WHERE sid = %d AND profile = '%s'", $object->sid, $profile->name));
          if ($object) {
            db_query("UPDATE {mapi_profile_settings} SET presenter ='%s', exts = '%s', derivative = '%s', settings ='%s' WHERE sid = %d",
              $object->presenter, '|'. implode('|', $object->exts) .'|', $object->derivative, serialize($object->settings), $object->sid);
          }
          else {
            $sid = db_next_id("{mapi_profile_settings}_sid");
            db_query("INSERT INTO {mapi_profile_settings} (sid, profile, presenter, exts, derivative, settings) VALUES (%d, '%s', '%s', '%s', '%s', '%s', '%s')",
              $sid, $profile->name, $object->presenter, '|'. implode('|', $object->exts) .'|', $object->derivative, serialize($object->settings));
            $object->sid = $sid;
            $profile->settings[$key] = $object;
          }
        }
      }
      break;

    case 'load':
      // load the details for the settings for the profile
      if ($profile->name) {
        $profile->settings = array();

        $results = db_query("SELECT sid, presenter, exts, derivative, settings FROM {mapi_profile_settings} WHERE profile ='%s'", $profile->name);
        while ($object = db_fetch_object($results)) {
          $object->exts = array_filter(explode('|', $object->exts));
          $object->settings = unserialize($object->settings);
          $profile->settings[$object->sid] = $object;
        }
      }
      break;

    case 'presenter':
      if ($profile->name && $profile->settings) {
        $ext = mapi_file_ext($filename);
        foreach ($profile->settings as $object) {
          if (in_array($ext, $object->exts)) {
            return $object->presenter;
          }
        }
      }
      break;

    case 'settings':
      if ($profile->name && $profile->settings) {
        $ext = mapi_file_ext($filename);
        foreach ($profile->settings as $object) {
          if (in_array($ext, $object->exts)) {
            return $object->settings;
          }
        }
      }
      break;

    case 'filename':
      if ($profile->name && $profile->settings) {
        $ext = mapi_file_ext($filename);
        foreach ($profile->settings as $object) {
          if (in_array($ext, $object->exts)) {
            if ($derivative && module_exists('mapi_derivative')) {
              return mapi_derive($filename, $derivative);
            }
            else {
              return $filename;
            }
          }
        }
      }
      break;

    // return list of profiles that this module handles
    case 'list':
      return mapi_profile_list();
  }
}

function _mapi_profile_form_validate($form_id, $form_values) {
  drupal_set_message('validating');
  // checks for changes to each presenter, including that the
  // presenter matches all of the extensions, and that the
  // derivative also matches the extensions.
}

function _mapi_profile_form_submit($form_id, $form_values) {
  // update the profiles based on validated input information
  // Check for values, if t('Add'), add an extra presenter
  // otherwise, modify the others.
  drupal_set_message('PROCESSING');
}
