<?php
// $Id$

/**
 *  Returns a list of the profiles currently available on the system.
 */
function mapi_profile_list($refresh = true) {
  static $cache;

  if (!isset($cache) || $refresh) {
    $cache = array();
    $results = db_query("SELECT * FROM {mapi_profiles} ORDER BY name ASC");
    while ($object = db_fetch_object($results)) {
      $cache[$object->pid] = $object->name;
    }
  }

  return $cache;
}

/**
 *  Creates a profile
 */
function mapi_profile_create($name) {
  $list = mapi_profile_list();
  if (!in_array($name, $list)) {
    $pid = db_next_id("{mapi_profiles}_pid");
    db_query("INSERT INTO {mapi_profiles} (pid, name) VALUES (%d, '%s')", $pid, $name);

    $object = db_fetch_object(db_query("SELECT * FROM {mapi_profiles} WHERE pid = %d", $pid));

    // notify of the creation of the profile
    mapi_invoke_profile('create', $object);

    return $object;
  }
  return false;
}

/**
 *  Deletes a profile
 */
function mapi_profile_delete($name) {
  $list = mapi_profile_list();
  if (in_array($name, $list)) {
    $object = mapi_profile_load($name);

    $pid = array_search($name, $list);
    db_query("DELETE FROM {mapi_profiles} WHERE pid = %d", $pid);

    // notify that profile has been deleted
    mapi_invoke_profile('delete', $object);

    return true;
  }

  return false;
}

/**
 *  Updates a profile
 */
function mapi_profile_update($profile) {
  if (!is_object($profile) || !in_array($profile->name, mapi_profile_list())) {
    return false;
  }

  // notify of update to profile
  mapi_invoke_profile('update', $profile);
}

/**
 *  Load a profile
 */
function mapi_profile_load($name, $refresh = true) {
  static $cache = array();

  if (!array_key_exists($name, $cache) || $refresh) {
    // only load profiles that have been created
    if (!in_array($name, mapi_profile_list())) {
      return false;
    }

    // load from database
    if ($object = db_fetch_object(db_query("SELECT * FROM {mapi_profiles} WHERE name='%s'", $name))) {
      // notify that the profile has been loaded
      mapi_invoke_profile('load', $object);

      $cache[$name] = $object;
    }
  }

  if (array_key_exists($name, $cache)) {
    return $cache[$name];
  }

  return false;
}

/**
 *  Check for existance of profile
 */
function mapi_profile_exists($name) {
  return in_array($name, mapi_profile_list());
}

/**
 *  The provides a presenter and settings in context
 */
function mapi_profile_details($filename, $profile) {
  //
  $presenter = mapi_invoke_profile('presenter', $profile, $filename);
  $settings = mapi_invoke_profile('settings', $profile, $filename);
  drupal_set_message('fixme: mapi_profile_details');
}
