<?php

/**
 * @defgroup tripal_featuremap Feature Map Module
 * @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');
require('includes/tripal_featuremap.form.inc');

/**
 *
 * @ingroup tripal_featuremap
 */
function tripal_featuremap_init() {
  //drupal_add_js(drupal_get_path('theme', 'tripal') . '/js/tripal_pub.js');
  drupal_add_css(drupal_get_path('theme', 'tripal') . '/css/tripal_featuremap.css');
}


/**
 * 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
  );
  
  // AJAX calls for adding/removing properties to a featuremap
  $items['tripal_featuremap/properties/add'] = array(
    'page callback' => 'tripal_featuremap_property_add',
    'access arguments' => array('edit chado_featuremap content'),
    'type ' => MENU_CALLBACK,
  );
  $items['tripal_featuremap/properties/description'] = array(
    'page callback' => 'tripal_featuremap_property_get_description',
    'access arguments' => array('edit chado_featuremap content'),
    'type ' => MENU_CALLBACK,
  );
  $items['tripal_featuremap/properties/minus/%/%'] = array(
    'page callback' => 'tripal_featuremap_property_delete',
    'page arguments' => array(3, 4),
    'access arguments' => array('edit chado_featuremap content'),
    '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_featurepos' => array(
      'arguments' => array('node' => NULL),
      'template' => 'tripal_featuremap_featurepos',
    ),
    'tripal_featuremap_publication' => array(
      'arguments' => array('node' => NULL),
      'template' => 'tripal_featuremap_publication',
    ),
    'tripal_featuremap_references' => array(
      'arguments' => array('node' => NULL),
      'template' => 'tripal_featuremap_references',
    ),
    'tripal_featuremap_admin' => array(
      'template' => 'tripal_featuremap_admin',
      'arguments' =>  array(NULL),
      'path' => drupal_get_path('module', 'tripal_featuremap') . '/theme'
    ),
    
    // Themed Forms
    'chado_featuremap_node_form' => array(
     'arguments' => array('form'),
    ),      
  );
}

/**
 * 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 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 the featuremap_id already exists then we got to the insert via 
  // a syncing operation.  We do not need to add the feature map
  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) {
      drupal_set_message(t('Unable to add featuremap.', 'warning'));
      watchdog('tripal_featuremap', 'Unable to create feature map where values: %values',
        array('%values' => print_r($values, TRUE)), WATCHDOG_WARNING);
      return;  
    }
    
    // now add the properties
    $properties = array(); // stores all of the properties we need to add
    $cross_refs = array(); // stores any cross references for this featuremap
  
    // get the list of properties for easy lookup (without doing lots of database queries
    $properties_list = array();
    $sql = "
      SELECT DISTINCT CVT.cvterm_id, CVT.name, CVT.definition
      FROM  {cvterm} CVT
        INNER JOIN {cv} ON CVT.cv_id = CV.cv_id
      WHERE 
        CV.name = 'featuremap_property' AND 
        NOT CVT.is_obsolete = 1
      ORDER BY CVT.name ASC 
    ";
    $prop_types = chado_query($sql);
    while ($prop = db_fetch_object($prop_types)) {
      $properties_list[$prop->cvterm_id] = $prop->name;
    }   
  
    // get the properties that should be added. Properties are in one of two forms:
    //  1) prop_value-[type id]-[index]
    //  2) new_value-[type id]-[index]
    //  3) new_id, new_value
    foreach ($node as $name => $value) {
      if (preg_match('/^new_value-(\d+)-(\d+)/', $name, $matches)) {
        $type_id = $matches[1];
        $index = $matches[2];
        $name = $properties_list[$type_id];
        $properties[$name][$index] = trim($value);
      }
    }
    if ($node->new_id and $node->new_value) {
      $type_id = $node->new_id;
      $index = count($properties[$name]);
      $name = $properties_list[$type_id];
      $properties[$name][$index] = trim($node->new_value);
    }
    
    // iterate through all of the properties to see if the Map dbxref is set, 
    // if so, add it to the $cross_refs array
    foreach ($properties as $name => $element) {
      foreach ($element as $index => $value) {
        if ($name == "Map Dbxref") {
          // we will add the cross-references to the featuremap_dbxref table
          // but we also want to keep the property in the featuremapprop table so don't unset it
          $cross_refs[] = $value;
        }
      }
    }
    
    // now add in the properties
    foreach ($properties as $property => $elements) {
      foreach ($elements as $rank => $value) {
         
        $status = tripal_featuremap_insert_property($featuremap['featuremap_id'], $property, $value, FALSE);
        if (!$status) {
          drupal_set_message("Error cannot add property: $property", "error");
          watchdog('t_featuremap', "Error cannot add property: %prop",
          array('%property' => $property), WATCHDOG_ERROR);
        }
      }
    }
  
    // add in any database cross-references
    foreach ($cross_refs as $index => $ref) {
      $featuremap_dbxref = tripal_featuremap_add_featuremap_dbxref($featuremap['featuremap_id'], trim($ref));
      if (!$featuremap_dbxref) {
        drupal_set_message("Error cannot add map cross reference: $ref", "error");
        watchdog('t_featuremap', "Error cannot add map cross reference: %ref",
        array('%ref' => $ref), WATCHDOG_ERROR);
      }
    }
  }

  // add the record to the chado_featuremap table in Drupal
  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']);
    }       
  }

  
  
  
}
/**
 * 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,
    'description' => $node->description,
    'unittype_id' => $node->unittype_id
  );
  $status = tripal_core_chado_update('featuremap', $match, $values);
  if (!$status) {
    drupal_set_message("Error updating map", "error");
    watchdog('t_featuremap', "Error updating map", array(), WATCHDOG_ERROR);
    return;
  }

  // now update the properties
  $properties = array(); // stores all of the properties we need to add
  $cross_refs = array(); // stores any cross references for this map
   
  // get the list of properties for easy lookup (without doing lots of database queries
  $properties_list = array();
  $sql = "
    SELECT DISTINCT CVT.cvterm_id, CVT.name, CVT.definition
    FROM  {cvterm} CVT
      INNER JOIN {cv} ON CVT.cv_id = CV.cv_id
    WHERE 
      CV.name = 'featuremap_property' AND 
      NOT CVT.is_obsolete = 1
    ORDER BY CVT.name ASC 
  ";
  $prop_types = chado_query($sql);
  while ($prop = db_fetch_object($prop_types)) {
    $properties_list[$prop->cvterm_id] = $prop->name;
  }
  
  // get the properties that should be added. Properties are in one of three forms:
  //  1) prop_value-[type id]-[index]
  //  2) new_value-[type id]-[index]
  //  3) new_id, new_value
  //  dpm($node);
  foreach ($node as $key => $value) {
    if (preg_match('/^prop_value-(\d+)-(\d+)/', $key, $matches)) {
      $type_id = $matches[1];
      $index = $matches[2];
      $name = $properties_list[$type_id];
      $properties[$name][$index] = trim($value);
    }
    if (preg_match('/^new_value-(\d+)-(\d+)/', $key, $matches)) {
      $type_id = $matches[1];
      $index = $matches[2];
      $name = $properties_list[$type_id];
      $properties[$name][$index] = trim($value);
    }
  }
  if ($node->new_id and $node->new_value) {
    $type_id = $node->new_id;
    $name = $properties_list[$type_id];
    $index = count($properties[$name]);
    $properties[$name][$index] = trim($node->new_value);
  }
  
  // iterate through all of the properties to see if the Map dbxref is set, 
  // if so, add it to the $cross_refs array
  foreach ($properties as $name => $element) {
    foreach ($element as $index => $value) {
      if ($name == "Map Dbxref") {
        // we will add the cross-references to the featuremap_dbxref table
        // but we also want to keep the property in the featuremapprop table so don't unset it
        $cross_refs[] = $value;
      }
    }
  }

  // now add in the properties by first removing any the featuremap
  // already has and adding the ones we have
  tripal_core_chado_delete('featuremapprop', array('featuremap_id' => $featuremap_id));
  foreach ($properties as $property => $elements) {
    foreach ($elements as $rank => $value) {
      $status = tripal_featuremap_insert_property($featuremap_id, $property, $value, FALSE);
      if (!$status) {
        drupal_set_message("Error cannot add property: '$property'", "error");
        watchdog('t_featuremap', "Error cannot add property: '%prop'",
        array('%prop' => $property), WATCHDOG_ERROR);
      }
    }
  }

  // add in any database cross-references after first removing
  tripal_core_chado_delete('featuremap_dbxref', array('featuremap_id' => $featuremap_id));
  foreach ($cross_refs as $index => $ref) {
    $featuremap_dbxref = tripal_featuremap_add_featuremap_dbxref($featuremap_id, trim($ref));
    if (!$featuremap_dbxref) {
      drupal_set_message("Error cannot add map cross reference: $ref", "error");
      watchdog('t_featuremap', "Error cannot add map cross reference: %ref",
      array('%ref' => $ref), WATCHDOG_ERROR);
    }
  }
}
/**
 *  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);
  
  // expand the description field as it is needed by the form
  $featuremap = tripal_core_expand_chado_vars($featuremap, 'field', 'featuremap.description');

  $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) {

}

function tripal_featuremap_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == "chado_featuremap_node_form") {
  }
}