<?php

/**
 * @defgroup tripal_featuremap Map
 * @ingroup tripal_modules
 * @{
 * Provides functions for managing chado maps including creating details pages for each map
 * @}
 */

require('api/tripal_featuremap.api.inc');
require('includes/tripal_featuremap.admin.inc');

/**
 * Display help and module information
 * @param path which path of the site we're displaying help
 * @param arg array that holds the current path as would be returned from arg()
 * function
 * @return help text for the path
 *
 * @ingroup tripal_featuremap
 */
function tripal_featuremap_help($path, $arg) {
  $output = '';
  switch ($path) {
    case "admin/help#tripal_featuremap":
      $output = '<p>'.
      t("Displays links to nodes created on this date") .
               '</p>';
      break;
  }
  return $output;
}

/**
 * Provide information to drupal about the node types that we're creating
 * in this module
 *
 * @ingroup tripal_featuremap
 */
function tripal_featuremap_node_info() {
  $nodes = array();
  $nodes['chado_featuremap'] = array(
      'name' => t('Map'),
      'module' => 'chado_featuremap',
      'description' => t('A feature map from the chado database (e.g. genetic map)'),
      'has_title' => FALSE,
      'title_label' => t('Feature Map'),
      'has_body' => FALSE,
      'body_label' => t('Feature Map Description'),
      'locked' => TRUE
  );
  return $nodes;
}

/**
 * Set the permission types that the chado module uses.  Essentially we
 * want permissionis that protect creation, editing and deleting of chado
 * data objects
 *
 * @ingroup tripal_featuremap
 */
function tripal_featuremap_perm() {
  return array(
    'access chado_featuremap content',
    'create chado_featuremap content',
    'delete chado_featuremap content',
    'edit chado_featuremap content',
    'administer tripal featuremap',
  );
}
/**
 *  Set the permission types that the module uses.
 *
 * @ingroup tripal_featuremap
 */
function chado_featuremap_access($op, $node, $account) {
  if ($op == 'create') {
    if (!user_access('create chado_featuremap content', $account)) {
      return FALSE;
    }
  }
  if ($op == 'update') {
    if (!user_access('edit chado_featuremap content', $account)) {
      return FALSE;
    }
  }
  if ($op == 'delete') {
    if (!user_access('delete chado_featuremap content', $account)) {
      return FALSE;
    }
  }
  if ($op == 'view') {
    if (!user_access('access chado_featuremap content', $account)) {
      return FALSE;
    }
  }
  return NULL;
}
/**
 * Menu items are automatically added for the new node types created
 * by this module to the 'Create Content' Navigation menu item.  This function
 * adds more menu items needed for this module.
 *
 * @ingroup tripal_featuremap
 */
function tripal_featuremap_menu() {
  $items = array();
  
  // The administative settings menu
  $items['admin/tripal/tripal_featuremap'] = array(
    'title' => 'Maps',
    'description' => 'Basic Description of Tripal Map Module Functionality',
    'page callback' => 'theme',
    'page arguments' => array('tripal_featuremap_admin'),
    'access arguments' => array('administer tripal featuremap'),
    'type' => MENU_NORMAL_ITEM,
  );

  $items['admin/tripal/tripal_featuremap/configuration'] = array(
    'title' => 'Configuration',
    'description' => 'Manage integration of Chado maps including associated features.',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('tripal_featuremap_admin'),
    'access arguments' => array('administer tripal featuremap'),
    'type' => MENU_NORMAL_ITEM,
  );

  // Synchronizing maps from Chado to Drupal
  $items['chado_sync_featuremaps'] = array(
    'title' => 'Sync Data',
    'page callback' => 'tripal_featuremap_sync_featuremaps',
    'access arguments' => array('administer tripal featuremap'),
    'type' => MENU_CALLBACK
  );
  
  return $items;
}

/**
 * Implements hook_views_api()
 * Purpose: Essentially this hook tells drupal that there is views support for
 *  for this module which then includes tripal_db.views.inc where all the
 *  views integration code is
 *
 * @ingroup tripal_featuremap
 */
function tripal_featuremap_views_api() {
  return array(
    'api' => 2.0,
  );
}



/**
 * Implementation of hook_nodeapi().
 * Display map information for associated features or organisms
 * This function also provides contents for indexing
 *
 * @ingroup tripal_featuremap
 */
function tripal_featuremap_nodeapi(&$node, $op, $teaser, $page) {

  switch ($op) {
    // Note that this function only adds map view to an organism/feature
    // node.
    case 'view':
      // add the map to the organism/feature search indexing
      if ($node->build_mode == NODE_BUILD_SEARCH_INDEX) {
        $node->content['tripal_featuremap_index_version'] = array(
          '#value' => theme('tripal_featuremap_search_index', $node),
        );
      }
      elseif ($node->build_mode == NODE_BUILD_SEARCH_RESULT) {
        $node->content['tripal_featuremap_index_version'] = array(
          '#value' => theme('tripal_featuremap_search_result', $node),
        );
      }      
  }
}

/**
 *  We need to let drupal know about our theme functions and their arguments.
 *  We create theme functions to allow users of the module to customize the
 *  look and feel of the output generated in this module
 *
 * @ingroup tripal_featuremap
 */
function tripal_featuremap_theme() {
  return array(
    'tripal_featuremap_search_index' => array(
       'arguments' => array('node'),
    ),
    'tripal_featuremap_search_result' => array(
       'arguments' => array('node'),
    ),
    'tripal_featuremap_base' => array(
       'arguments' => array('node' => NULL),
       'template' => 'tripal_featuremap_base',
    ),
    'tripal_featuremap_properties' => array(
      'arguments' => array('node' => NULL),
      'template' => 'tripal_featuremap_properties',
    ),
    'tripal_featuremap_publication' => array(
      'arguments' => array('node' => NULL),
      'template' => 'tripal_featuremap_publication',
    ),
    'tripal_featuremap_admin' => array(
      'template' => 'tripal_featuremap_admin',  
      'arguments' =>  array(NULL),  
      'path' => drupal_get_path('module', 'tripal_featuremap') . '/theme' 
    ),
  );
}

/**
 * This function is an extension of the chado_feature_view and
 * chado_organism_view by providing the markup for the map object
 * THAT WILL BE INDEXED.
 *
 * @ingroup tripal_featuremap
 */
function theme_tripal_featuremap_search_index($node) {
}

/**
 *
 * @ingroup tripal_featuremap
 */
function tripal_featuremap_cron() {

}
/**
 *  The following function proves access control for users trying to
 *  perform actions on data managed by this module
 *
 * @ingroup tripal_featuremap
 */
function tripal_featuremap_map_access($op, $node, $account) {
  if ($op == 'create') {
    if (!user_access('create chado_featuremap content', $account)) {
      return FALSE;
    }
  }

  if ($op == 'update') {
    if (!user_access('edit any chado_featuremap content', $account) &&
        !user_access('edit own chado_featuremap content', $account)) {
        return FALSE;
    }
    if (user_access('edit own chado_featuremap content', $account) &&
      $account->uid != $node->uid) {
      return FALSE;
    }
  }

  if ($op == 'delete') {
    if (!user_access('delete any chado_featuremap content', $account) &&
      !user_access('delete own chado_featuremap content', $account)) {
      return FALSE;
    }
    if (user_access('delete own chado_featuremap content', $account) &&
      $account->uid != $node->uid) {
      return FALSE;
    }
  }
  return NULL;
}

/**
 *  When editing or creating a new node of type 'chado_featuremap' we need
 *  a form.  This function creates the form that will be used for this.
 *
 * @ingroup tripal_featuremap
 */
function chado_featuremap_form($node) {
  $type = node_get_types('type', $node);  
  $form = array();

  $featuremap = $node->featuremap;

  // keep track of the map id if we have.  If we do have one then
  // this is an update as opposed to an insert.
  $form['featuremap_id'] = array(
    '#type' => 'value',
    '#value' => $featuremap->featuremap_id,
  );

  $form['title']= array(
    '#type'          => 'textfield',
    '#title'         => t('Map Name'),
    '#description'   => t('Please enter a name for this map'),
    '#required'      => TRUE,
    '#default_value' => $featuremap->name,
  );

  $form['description']= array(
    '#type'          => 'textarea',
    '#title'         => t('Map Description'),
    '#description'   => t('A description of the map.'),
    '#required'      => TRUE,
    '#default_value' => $featuremap->description,
  );
  
  // get the list of unit types
  $values = array(
    'cv_id' => array(
      'name' => 'tripal_featuremap',
    )
  );
  $columns = array('cvterm_id','name');
  $options = array('order_by' => array('name' => 'ASC'));
  $featuremap_units = tripal_core_chado_select('cvterm', $columns, $values, $options);
  $units = array();
  $units[''] = '';
  foreach($featuremap_units as $unit) {
    $units[$unit->cvterm_id] = $unit->name;
  }

  $form['unittype_id'] = array(
    '#title'       => t('Map Units'),
    '#type'        => t('select'),
    '#description' => t("Chose the units for this map"),
    '#required'    => TRUE,
    '#default_value' => $featuremap->unittype_id->cvterm_id,
    '#options'     => $units,
  );

  return $form;
}
/**
 *  validates submission of form when adding or updating a map node
 *
 * @ingroup tripal_featuremap
 */
function chado_featuremap_validate($node) {
  $map = 0;
  // check to make sure the unique name on the map is unique
  // before we try to insert into chado. If this is an update then we will
  // have a featuremap_id, therefore we want to look for another map with this 
  // name but with a different featuremap_id. If this is an insert, just look
  // for a case where the name already exists.
  if ($node->featuremap_id) {
    $sql = "SELECT * FROM ".
           "{featuremap} WHERE ".
           "name = '%s' ".
           "AND NOT featuremap_id = %d";
    $map = db_fetch_object(chado_query($sql, $node->title, $node->featuremap_id));
  }
  else {
    $sql = "SELECT * FROM ".
           "{featuremap} ".
           "WHERE name = '%s'";
    $map = db_fetch_object(chado_query($sql, $node->title));
  }
  if ($map) {
    form_set_error('name', t('The unique map name already exists. Please choose another'));
  }
}

/**
 *  When a new chado_featuremap node is created we also need to add information
 *  to our chado_featuremap table.  This function is called on insert of a new node
 *  of type 'chado_featuremap' and inserts the necessary information.
 *
 * @ingroup tripal_featuremap
 */
function chado_featuremap_insert($node) {

  if ($node->featuremap_id) {
    $featuremap['featuremap_id'] = $node->featuremap_id;
  }
  else {
    $values = array(
      'name' => $node->title,
      'description' => $node->description,
      'unittype_id' => $node->unittype_id
    );
    $featuremap = tripal_core_chado_insert('featuremap', $values);
  }

  if ($featuremap) {
    // make sure the entry for this feature doesn't already exist in the chado_featuremap table
    // if it doesn't exist then we want to add it.
    $featuremap_id = chado_get_id_for_node('featuremap', $node) ;
    if (!$featuremap_id) {
       // next add the item to the drupal table
      $sql = "INSERT INTO {chado_featuremap} (nid, vid, featuremap_id) ".
            "VALUES (%d, %d, %d)";
      db_query($sql, $node->nid, $node->vid, $featuremap['featuremap_id']);
    }
  }
  else {
    drupal_set_message(t('Unable to add featuremap.', 'warning'));
    watchdog('tripal_featuremap',
    'Insert feature: Unable to create featuremap where values: %values',
    array('%values' => print_r($values, TRUE)),
    WATCHDOG_WARNING
    );
  }
}
/**
 * Update nodes
 *
 * @ingroup tripal_featuremap
 */
function chado_featuremap_update($node) {
  if ($node->revision) {
    // there is no way to handle revisions in Chado but leave
    // this here just to make not we've addressed it.
  }
  $featuremap_id = chado_get_id_for_node('featuremap', $node) ;

  // update the map record
  $match = array(
    'featuremap_id' => $featuremap_id,
  );
  $values = array(
    'name' => $node->title,
    'unittype_id' => $node->unittype_id
  );
  $status = tripal_core_chado_update('featuremap', $match, $values);  
}
/**
 *  When a node is requested by the user this function is called to allow us
 *  to add auxiliary data to the node object.
 *
 * @ingroup tripal_featuremap
 */
function chado_featuremap_load($node) {
  // get the feature details from chado
  $featuremap_id = chado_get_id_for_node('featuremap', $node);

  $values = array('featuremap_id' => $featuremap_id);
  $featuremap = tripal_core_generate_chado_var('featuremap', $values);

  $additions = new stdClass();
  $additions->featuremap = $featuremap;
  return $additions;

}
/**
 *  This function customizes the view of the chado_featuremap node.  It allows
 *  us to generate the markup. This function is required for node [Preview]
 *
 * @ingroup tripal_featuremap
 */
function chado_featuremap_view($node, $teaser = FALSE, $page = FALSE) {
   // use drupal's default node view:
  if (!$teaser) {

    $node = node_prepare($node, $teaser);    
  }
  return $node;
}

/**
 * Delete data from drupal and chado databases when a node is deleted
 * @ingroup tripal_featuremap
 */
function chado_featuremap_delete(&$node) {

  $featuremap_id = chado_get_id_for_node('featuremap', $node);
  
  // if we don't have a map id for this node then this isn't a node of
  // type chado_featuremap or the entry in the chado_featuremap table was lost.
  if (!$featuremap_id) {
    return;
  }
  
  // Remove data from {chado_featuremap}, {node} and {node_revisions} tables of
  // drupal database
  $sql_del = "DELETE FROM {chado_featuremap} ".
            "WHERE nid = %d ".
            "AND vid = %d";
  db_query($sql_del, $node->nid, $node->vid);
  $sql_del = "DELETE FROM {node} ".
            "WHERE nid = %d ".
            "AND vid = %d";
  db_query($sql_del, $node->nid, $node->vid);
  $sql_del = "DELETE FROM {node_revisions} ".
            "WHERE nid = %d ".
            "AND vid = %d";
  db_query($sql_del, $node->nid, $node->vid);

  // Remove data from map and mapprop tables of chado database as well
  chado_query("DELETE FROM {featuremap} WHERE featuremap_id = %d", $featuremap_id);
  chado_query("DELETE FROM {featuremapprop} WHERE featuremap_id = %d", $featuremap_id);
}

/*
 * 
 */
function theme_tripal_featuremap_search_result($node) {

}