<?php

/**
 * @defgroup tripal_library Library Module
 * @ingroup tripal_modules
 * @{
 * Provides functions for managing chado libraries including creating details pages for each library
 * @}
 */

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

/**
 * Provide information to drupal about the node types that we're creating
 * in this module
 *
 * @ingroup tripal_library
 */
function tripal_library_node_info() {
  $nodes = array();
  $nodes['chado_library'] = array(
    'name' => t('Library'),
    'base' => 'chado_library',
    'description' => t('A library from the chado database'),
    'has_title' => FALSE,
    'title_label' => t('Library'),
    'has_body' => FALSE,
    '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_library
 */
function tripal_library_permisssions() {
  return array(
    'access chado_library content' => array(
      'title' => t('View Libraries'),
      'description' => t('Allow users to view library pages.'),
    ),
    'create chado_library content' => array(
      'title' => t('Create Libraries'),
      'description' => t('Allow users to create new library pages.'),
    ),
    'delete chado_library content' => array(
      'title' => t('Delete Libraries'),
      'description' => t('Allow users to delete library pages.'),
    ),
    'edit chado_library content' => array(
      'title' => t('Edit Libraries'),
      'description' => t('Allow users to edit library pages.'),
    ),
    'adminster tripal library' => array(
      'title' => t('Administer Libraries'),
      'description' => t('Allow users to administer all libraries.'),
    ),
  );
}
/**
 * Implement hook_access().
 *
 * This hook allows node modules to limit access to the node types they define.
 *
 *  @param $node
 *  The node on which the operation is to be performed, or, if it does not yet exist, the
 *  type of node to be created
 *
 *  @param $op
 *  The operation to be performed
 *
 *  @param $account
 *  A user object representing the user for whom the operation is to be performed
 *
 *  @return
 *  If the permission for the specified operation is not set then return FALSE. If the
 *  permission is set then return NULL as this allows other modules to disable
 *  access.  The only exception is when the $op == 'create'.  We will always
 *  return TRUE if the permission is set.
 *
 * @ingroup tripal_library
 */
function chado_library_node_access($node, $op, $account) {
  if ($op == 'create') {
    if (!user_access('create chado_library content', $account)) {
      return FALSE;
    }
    return TRUE;
  }
  if ($op == 'update') {
    if (!user_access('edit chado_library content', $account)) {
      return FALSE;
    }
  }
  if ($op == 'delete') {
    if (!user_access('delete chado_library content', $account)) {
      return FALSE;
    }
  }
  if ($op == 'view') {
    if (!user_access('access chado_library 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_library
 */
function tripal_library_menu() {
  $items = array();
  // The administative settings menu
  $items['admin/tripal/tripal_library'] = array(
    'title' => 'Libraries',
    'description' => 'Basic Description of Tripal Library Module Functionality',
    'page callback' => 'theme',
    'page arguments' => array('tripal_library_help'),
    'access arguments' => array('administer tripal libraries'),
    'type' => MENU_NORMAL_ITEM,
  );

  $items['admin/tripal/tripal_library/configuration'] = array(
    'title' => 'Configuration',
    'description' => 'Configure the Tripal Library module',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('tripal_library_help'),
    'access arguments' => array('administer tripal libraries'),
    'type' => MENU_NORMAL_ITEM,
  );

  // Synchronizing libraries from Chado to Drupal
  $items['chado_sync_libraries'] = array(
    'title' => 'Sync Library Data',
    'page callback' => 'tripal_library_sync_libraries',
    'access arguments' => array('administer tripal libraries'),
    '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_library
 */
function tripal_library_views_api() {
  return array(
    'api' => 2.0,
  );
}

/**
 * @ingroup tripal_library
 */
function tripal_library_node_view(&$node, $view_mode, $langcode) {

  switch ($node->type) {
    case 'chado_organism':
      if ($view_mode == 'full') {
        $node->content['tripal_organism_libraries'] = array(
          '#value' => theme('tripal_organism_libraries', $node),
        );
      }
      break;
    case 'chado_feature':
      if ($view_mode == 'full') {
        $node->content['tripal_feature_libraries'] = array(
          '#value' => theme('tripal_feature_libraries', $node),
        );
      }
      break;
  }
}
/**
 *  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_library
 */
function tripal_library_theme() {
  $theme_path = drupal_get_path('module', 'tripal_library') . '/theme';
  $items = array(
    // themed functions
    'tripal_library_library_table' => array(
      'arguments' => array('libraries'),
    ),
    'tripal_library_search_index' => array(
      'arguments' => array('node'),
    ),
    'tripal_library_search_result' => array(
      'arguments' => array('node'),
    ),
    // tripal_organism templates
    'tripal_organism_libraries' => array(
      'arguments' => array('node' => NULL),
      'template' => 'tripal_organism_libraries',
      'path' => "$theme_path/tripal_organism",
    ),
    // tripal_feature templates
    'tripal_feature_libraries' => array(
      'arguments' => array('node' => NULL),
      'template' => 'tripal_feature_libraries',
      'path' => "$theme_path/tripal_feature",
    ),
    // tripal_library templates
    'tripal_library_base' => array(
      'arguments' => array('node' => NULL),
      'template' => 'tripal_library_base',
      'path' => "$theme_path/tripal_library",
    ),
    'tripal_library_synonyms' => array(
      'arguments' => array('node' => NULL),
      'template' => 'tripal_library_synonyms',
      'path' => "$theme_path/tripal_library",
    ),
    'tripal_library_references' => array(
      'arguments' => array('node' => NULL),
      'template' => 'tripal_library_references',
      'path' => "$theme_path/tripal_library",
    ),
    'tripal_library_properties' => array(
      'arguments' => array('node' => NULL),
      'template' => 'tripal_library_properties',
      'path' => "$theme_path/tripal_library",
    ),
    'tripal_library_terms' => array(
      'arguments' => array('node' => NULL),
      'template' => 'tripal_library_terms',
      'path' => "$theme_path/tripal_library",
    ),
    // help template
    'tripal_library_help' => array(
      'template' => 'tripal_library_help',
      'arguments' =>  array(NULL),
      'path' => $theme_path,
    ),
  );
  return $items;
}

/**
 * Implements hook_help()
 * Purpose: Adds a help page to the module list
 */
function tripal_library_help ($path, $arg) {
  if ($path == 'admin/help#tripal_library') {
    return theme('tripal_library_help', array());
  }
}
/**
 * @ingroup tripal_library
 */
function tripal_library_block_info() {

  $blocks['libreferences']['info'] = t('Tripal Library Cross References');
  $blocks['libreferences']['cache'] = DRUPAL_NO_CACHE;

  $blocks['libbase']['info'] = t('Tripal Library Details');
  $blocks['libbase']['cache'] = DRUPAL_NO_CACHE;

  $blocks['libterms']['info'] = t('Tripal Library Terms');
  $blocks['libterms']['cache'] = DRUPAL_NO_CACHE;

  $blocks['libsynonyms']['info'] = t('Tripal Library Synonyms');
  $blocks['libsynonyms']['cache'] = DRUPAL_NO_CACHE;

  $blocks['libproperties']['info'] = t('Tripal Library Properties');
  $blocks['libproperties']['cache'] = DRUPAL_NO_CACHE;

  $blocks['featurelibs']['info'] = t('Tripal Feature Libraries');
  $blocks['featurelibs']['cache'] = DRUPAL_NO_CACHE;

  $blocks['orglibs']['info'] = t('Tripal Organism Libraries');
  $blocks['orglibs']['cache'] = DRUPAL_NO_CACHE;

  return $blocks;
}
/**
 * @ingroup tripal_library
 */
function tripal_library_block_view($delta = '') {

  if (user_access('access chado_library content') and arg(0) == 'node' and is_numeric(arg(1))) {
    $nid = arg(1);
    $node = node_load($nid);

    $block = array();
    switch ($delta) {
      case 'libreferences':
        $block['subject'] = t('Cross References');
        $block['content'] = theme('tripal_library_references', $node);
        break;
      case 'libbase':
        $block['subject'] = t('Library Details');
        $block['content'] = theme('tripal_library_base', $node);
        break;
      case 'libsynonyms':
        $block['subject'] = t('Synonyms');
        $block['content'] = theme('tripal_library_synonyms', $node);
        break;
      case 'libproperties':
        $block['subject'] = t('Properties');
        $block['content'] = theme('tripal_library_properties', $node);
        break;
      case 'libterms':
        $block['subject'] = t('Library Terms');
        $block['content'] = theme('tripal_library_terms', $node);
        break;
      case 'featurelibs':
        $block['subject'] = t('Libraries');
        $block['content'] = theme('tripal_feature_libraries', $node);
        break;
      case 'orglibs':
        $block['subject'] = t('Libraries');
        $block['content'] = theme('tripal_organism_libraries', $node);
        break;
      default :
    }
    return $block;
  }
}
/**
 * This function is an extension of the chado_feature_view and
 * chado_organism_view by providing the markup for the library object
 * THAT WILL BE INDEXED.
 *
 * @ingroup tripal_library
 */
function theme_tripal_library_search_index($node) {

  if ($node->type == 'chado_organism') {
    $content = "";
    // get the libraries for the organism
    $sql = "SELECT * FROM {library} L WHERE L.organism_id = :organism_id";
    $libraries = array();
    $results = chado_query($sql, array(':organism_id' => $node->organism->organism_id));
    while ($library = $results->fetchObject()) {
      // get the description
      $sql = "
        SELECT *
        FROM {libraryprop} LP
          INNER JOIN {cvterm} CVT ON CVT.cvterm_id = LP.type_id
        WHERE LP.library_id = :library_id
          AND CVT.name = 'library_description'
      ";
      $desc = chado_query($sql, array(':library_id' => $library->library_id))->fetchObject();
      $library->description = $desc->value;
      $libraries[] = $library;
    }
    if (count($libraries) > 0) {
      foreach ($libraries as $library) {
        $content .= "$library->name ";
        $content .= "$library->description";
      };
    }
    // Provide library names to show in a feature page
  }
  elseif ($node->type == 'chado_feature') {
    $content = "";
    $organism_id = $node->feature->organism_id;
    $sql = "
      SELECT *
      FROM {library} L
        INNER JOIN {library_feature} LF ON L.library_id = LF.library_id
      WHERE LF.feature_id = :feature_id
    ";
    $libraries = array();
    $results = chado_query($sql, array(':feature_id' => $node->feature->feature_id));
    while ($library = $results->fetchObject()) {
      $libraries[] = $library;
    }
    if (count($libraries) > 0) {
      $lib_additions = array();
      foreach ($libraries as $library) {
        $content .= $library->name;
      };
    }
  }
  return $content;
}

/**
 * This function shows library information on an organism/feature node
 *
 * @ingroup tripal_library
 */
function theme_tripal_library_node_libraries($node) {
  $content = "";

  // Show library information in a expandable box for a organism page.
  // Make sure we have $node->organism_id. In the case of creating a new
  // organism, the organism_id is not created until we save. This will cause
  // an error when users preview the creation without a $node->organism_id
  if ($node->type == 'chado_organism' && $node->organism_id) {
    $box_status = variable_get("tripal_library-box-libraries", "menu_off");

    if (strcmp($box_status, "menu_off")==0) {
      return get_tripal_library_organism_libraries($node->nid);
    }
  }
  // Provide library names to show in a feature page.
  // Make sure we have $node->feature->feature_id or there will be an error
  // when a feature is previewed at its creation
  elseif ($node->type == 'chado_feature' && $node->feature->feature_id) {
    $organism_id = $node->feature->organism_id;
    $sql = "
      SELECT *
      FROM {library} L
        INNER JOIN Library_feature LF ON L.library_id = LF.library_id
      WHERE LF.feature_id = :feature_id
    ";
    $libraries = array();
    $results = chado_query($sql, array(':feature_id' => $node->feature->feature_id));
    while ($library = $results->fetchObject()) {
      $libraries[] = $library;
  }
  if (count($libraries) > 0) {
    $lib_additions = array();
    foreach ($libraries as $library) {
      $sql = "SELECT nid FROM {chado_library} WHERE library_id = :library_id";
      $lib_nid = db_query($sql, array(':library_id' => $library->library_id))->fetchField();
      if ($lib_nid) {
        $lib_url = url("node/$lib_nid");
      }
      $lib_additions[$lib_url] = $library->name;
    };
    $node->lib_additions = $lib_additions;
  }
  }
  return $content;
}


/**
 *
 * @ingroup tripal_library
 */
function tripal_library_cron() {

}


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

  $library = $node->library;

  // get the default values
  $uniquename = $node->uniquename;
  if (!$uniquename) {
    $uniquename = $library->uniquename;
  }
  $library_type = $node->library_type;
  if (!$library_type) {
    $library_type = $library->type_id->cvterm_id;
  }
  $organism_id = $node->organism_id;
  if (!$organism_id) {
    $organism_id = $library->organism_id->organism_id;
  }
  $library_description = $node->library_description;
  if (!$library_description) {
    $libprop = tripal_library_get_property($library->library_id, 'library_description');
    $library_description = $libprop->value;
  }

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

  $form['title']= array(
    '#type'          => 'textfield',
    '#title'         => t('Library Title'),
    '#description'   => t('Please enter the title for this library. '.
                          'This appears at the top of the library page.'),
    '#required'      => TRUE,
    '#default_value' => $node->title,
    '#weight'        => 1
  );

  $form['uniquename']= array(
    '#type'          => 'textfield',
    '#title'         => t('Unique Library Name'),
    '#description'   => t('Please enter a unique name for this library'),
    '#required'      => TRUE,
    '#default_value' => $uniquename,
    '#weight'        => 2
  );

  // get the list of library types
  $values = array(
    'cv_id' => array(
      'name' => 'tripal_library_types',
    )
  );
  $columns = array('cvterm_id','name');
  $options = array('order_by' => array('name' => 'ASC'));
  $lib_types = tripal_core_chado_select('cvterm', $columns, $values, $options);
  $types = array();
  $types[''] = '';
  foreach($lib_types as $type) {
    $types[$type->cvterm_id] = $type->name;
  }

  $form['library_type'] = array(
    '#title'       => t('Library Type'),
    '#type'        => t('select'),
    '#description' => t("Choose the library type."),
    '#required'    => TRUE,
    '#default_value' => $library_type,
    '#options'     => $types,
    '#weight'      => 3
  );

  // get the list of organisms
  $sql = "SELECT * FROM {organism}";
  $org_rset = chado_query($sql);

  $organisms = array();
  $organisms[''] = '';
  while ($organism = $org_rset->fetchObject()) {
    $organisms[$organism->organism_id] =
    "$organism->genus $organism->species ($organism->common_name)";
  }

  $form['organism_id'] = array(
   '#title'       => t('Organism'),
   '#type'        => t('select'),
   '#description' => t("Choose the organism with which this library is ".
                       "associated."),
   '#required'    => TRUE,
   '#default_value' => $organism_id,
   '#options'     => $organisms,
   '#weight'      => 4,
  );

  $form['library_description']= array(
    '#type'          => 'textarea',
    '#title'         => t('Library Description'),
    '#description'   => t('A brief description of the library'),
    '#required'      => TRUE,
    '#default_value' => $library_description,
    '#weight'        => 5
  );

  return $form;
}
/**
 *  validates submission of form when adding or updating a library node
 *
 * @ingroup tripal_library
 */
function chado_library_validate($node) {
  $lib = 0;
  // check to make sure the unique name on the library is unique
  // before we try to insert into chado.
  if ($node->library_id) {
    $sql = "
      SELECT *
      FROM {library}
      WHERE uniquename = :uname AND NOT library_id = :library_id
    ";
    $lib = chado_query($sql, array(':uname' => $node->uniquename, ':library_id' => $node->library_id))->fetchObject();
  }
  else {
    $sql = "SELECT * FROM {library} WHERE uniquename = :uname";
    $lib = chado_query($sql, array(':uname' => $node->uniquename))->fetchObject();
  }
  if ($lib) {
    form_set_error('uniquename', t('The unique library name already exists. Please choose another'));
  }
}
/**
 *  When a new chado_library node is created we also need to add information
 *  to our chado_library table.  This function is called on insert of a new node
 *  of type 'chado_library' and inserts the necessary information.
 *
 * @ingroup tripal_library
 */
function chado_library_insert($node) {

  if ($node->library_id) {
    $library['library_id'] = $node->library_id;
  }
  else {
    $values = array(
      'name' => $node->title,
      'uniquename' => $node->uniquename,
      'organism_id' => $node->organism_id,
      'type_id' => $node->library_type,
    );
    $library = tripal_core_chado_insert('library', $values);
  }

  if ($library) {
     // add the description property
    tripal_library_insert_property($library['library_id'], 'library_description',
      $node->library_description);

    // make sure the entry for this feature doesn't already exist in the chado_library table
    // if it doesn't exist then we want to add it.
    $library_id = chado_get_id_for_node('library', $node->nid) ;
    if (!$library_id) {
       // next add the item to the drupal table
      $sql = "
        INSERT INTO {chado_library} (nid, vid, library_id)
        VALUES (:nid, :vid, :library_id)
      ";
      db_query($sql, array(':nid' => $node->nid, ':vid' => $node->vid, ':library_id' => $library['library_id']));
    }
  }
  else {
    drupal_set_message(t('Unable to add library.', 'warning'));
    watchdog('tripal_library', 'Insert feature: Unable to create library where values: %values',
      array('%values' => print_r($values, TRUE)), WATCHDOG_WARNING);
  }
}
/**
 * Update nodes
 *
 * @ingroup tripal_library
 */
function chado_library_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.
  }

  $library_id = chado_get_id_for_node('library', $node->nid);
  // update the library record
  $match = array(
     'library_id' => $library_id,
  );
  $values = array(
     'name' => $node->title,
     'uniquename' => $node->uniquename,
     'organism_id' => $node->organism_id,
     'type_id' => $node->library_type,
  );
  $status = tripal_core_chado_update('library', $match, $values);

  tripal_library_update_property($library_id, 'library_description', $node->library_description, 1);

}
/**
 *  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_library
 */
function chado_library_load($node) {
  // get the feature details from chado
  $library_id = chado_get_id_for_node('library', $node->nid);

  $values = array('library_id' => $library_id);
  $library = tripal_core_generate_chado_var('library', $values);

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

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

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

    // If Hook_view() is called by Hook_form(), we'll only have orgnism_id
    // but not genus/species/common_name. We need to get those from chado
    // database so they will show up in preview
    if (!$node->genus) {
      $sql = "SELECT * FROM {organism} WHERE organism_id = :organism_id";
      $data = chado_query($sql, array(':organism_id' => $node->organism_id))->fetchObject();
      $node->genus = $data->genus;
      $node->species = $data->species;
      $node->common_name = $data->common_name;
    }
  }
  return $node;
}

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

  $library_id = chado_get_id_for_node('library', $node->nid);

  // if we don't have a library id for this node then this isn't a node of
  // type chado_library or the entry in the chado_library table was lost.
  if (!$library_id) {
    return;
  }

  // Remove data from {chado_library}, {node} and {node_revisions} tables of
  // drupal database
  $sql_del = "DELETE FROM {chado_library} WHERE nid = :nid AND vid = :vid";
  db_query($sql_del, array(':nid' => $node->nid, ':vid' => $node->vid));
  $sql_del = "DELETE FROM {node_revision} WHERE nid = :nid AND vid = :vid";
  db_query($sql_del, array(':nid' => $node->nid, ':vid' => $node->vid));
  $sql_del = "DELETE FROM {node} WHERE nid = :nid AND vid = :vid";
  db_query($sql_del, array(':nid' => $node->nid, ':vid' => $node->vid));

  // Remove data from library and libraryprop tables of chado database as well
  chado_query("DELETE FROM {libraryprop} WHERE library_id = :library_id", array(':library_id' => $library_id));
  chado_query("DELETE FROM {library} WHERE library_id = :library_id", array(':library_id' => $library_id));
}