<?php
/**
 * @file
 * Implements hooks from the Schema API.
 *
 * @ingroup tripal_analysis
 */

/**
 * Implements hook_disable().
 * Disable default views when module is disabled
 *
 * @ingroup tripal_analysis
 */
function tripal_analysis_disable() {

  // Disable all default views provided by this module
  require_once("tripal_analysis.views_default.inc");
  $views = tripal_analysis_views_default_views();
  foreach (array_keys($views) as $view_name) {
    tripal_disable_view($view_name,FALSE,array('suppress_error' => TRUE));
  }

}

/**
 * Implementation of hook_requirements().
 *
 * @ingroup tripal_analysis
 */
function tripal_analysis_requirements($phase) {
  $requirements = array();
  if ($phase == 'install') {
    // make sure chado is installed
    if (!$GLOBALS["chado_is_installed"]) {
      $requirements ['tripal_analysis'] = array(
            'title' => "tripal_analysis",
            'value' => "ERROR: Chado must be installed before this module can be enabled",
            'severity' => REQUIREMENT_ERROR,
      );
    }
  }
  return $requirements;
}

/**
 * Implementation of hook_install().
 *
 * @ingroup tripal_analysis
 */
function tripal_analysis_install() {

  // we may need the analysisfeatureprop table if it doesn't already exist
  tripal_analysis_create_analysisfeatureprop();

  // add vocabularies
  tripal_analysis_add_cvs();

  // add cvterms
  tripal_analysis_add_cvterms();

  // add materialized views
  tripal_analysis_add_mview_analysis_organism();

  // set the default vocabularies
  tripal_set_default_cv('analysisprop', 'type_id', 'analysis_property');
}

/**
 * Implementation of hook_uninstall().
 *
 * @ingroup tripal_analysis
 */
function tripal_analysis_uninstall() {

}

/**
 * Create a legacy custom chado table (analysisfeatureprop) to store properties of
 * analysisfeature links.
 *
 * @ingroup tripal_analysis
 */
function tripal_analysis_create_analysisfeatureprop() {

  // Create analysisfeatureprop table in chado.  This is needed for Chado
  // version 1.11, the table exists in Chado 1.2.
  if (!db_table_exists('chado.analysisfeatureprop')) {
    $sql = "
      CREATE TABLE {analysisfeatureprop} (
        analysisfeatureprop_id SERIAL PRIMARY KEY,
        analysisfeature_id     INTEGER NOT NULL,
        type_id                INTEGER NOT NULL,
        value                  TEXT,
        rank                   INTEGER NOT NULL,
        CONSTRAINT analysisfeature_id_type_id_rank UNIQUE (analysisfeature_id, type_id, rank),
        CONSTRAINT analysisfeatureprop_analysisfeature_id_fkey FOREIGN KEY (analysisfeature_id) REFERENCES {analysisfeature}(analysisfeature_id) ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED,
        CONSTRAINT analysisfeatureprop_type_id_fkey FOREIGN KEY (type_id) REFERENCES {cvterm}(cvterm_id) ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED
      )
    ";
    chado_query($sql);
  }
}

/**
 * Add cvs related to analyses
 *
 * @ingroup tripal_analysis
 */
function tripal_analysis_add_cvs() {

  // typically here we would add the analysis_property vocabulary
  // but it already comes with Chado.

}

/**
 * Adds controlled vocabulary terms needed by this module.
 *
 * @ingroup tripal_analysis
 */
function tripal_analysis_add_cvterms() {

  tripal_insert_cv(
    'tripal_analysis',
    'Terms used for managing analyses in Tripal'
  );

  // add analysis_date.  This is no longer used (as far as we can tell) but we don't
  // get rid of it in case it is used, so just keep it in the Tripal CV
  tripal_insert_cvterm(
    array(
      'name' => 'analysis_date',
      'definition' => 'The date that an analysis was performed.',
      'cv_name' => 'tripal',
      'is_relationship' => 0,
      'db_name' => 'tripal'
    ),
    array('update_existing' => TRUE)
  );

  // add analysis_short_name.  This is no longer used (as far as we can tell) but we don't
  // get rid of it in case it is used, so just keep it in the Tripal CV
  tripal_insert_cvterm(
    array(
      'name' => 'analysis_short_name',
      'definition' => 'A computer legible (no spaces or special characters) '
        . 'abbreviation for the analysis.',
      'cv_name' => 'tripal',
      'is_relationship' => 0,
      'db_name' => 'local'
    ),
    array('update_existing' => TRUE)
  );


  // the 'analysis_property' vocabulary is for user definable properties wo we
  // will add an 'Analysis Type' to this vocubulary
  tripal_insert_cvterm(
    array(
      'name' => 'Analysis Type',
      'definition' => 'The type of analysis that was performed.',
      'cv_name' => 'analysis_property',
      'is_relationship' => 0,
      'db_name' => 'local'
    ),
    array('update_existing' => TRUE)
  );
}

/**
 * Implementation of hook_schema().
 *
 * - chado_analysis table
 *     stores nodes that are also saved in the analysis table of chado database.
 * - tripal_analysis table
 *     stores the sub-module names, such as tripal_analysis_blast, that are registered
 *     with this module.
 *
 * @ingroup tripal_analysis
 */
function tripal_analysis_schema() {

  // chado_analysis table
  $schema['chado_analysis'] = array(
    'fields' => array(
      'vid' => array(
        'type' => 'int',
        'unsigned' => TRUE,
        'not null' => TRUE,
        'default' => 0
      ),
      'nid' => array(
        'type' => 'int',
        'unsigned' => TRUE,
        'not null' => TRUE,
        'default' => 0
      ),
      'analysis_id' => array(
        'type' => 'int',
        'not null' => TRUE,
        'default' => 0
      )
    ),
    'indexes' => array(
      'analysis_id' => array('analysis_id')
    ),
    'unique keys' => array(
      'nid_vid' => array('nid', 'vid'),
      'vid' => array('vid')
    ),
    'primary key' => array('nid'),
  );

  // tripal_analysis table
  $schema['tripal_analysis'] = array(
    'description' => 'Table to store analysis sub-modules',
    'fields' => array(
      'modulename' => array(
        'type' => 'text',
        'size' => 'small',
        'not null' => TRUE,
        'description' => 'The module name. Tripal Analysis will use the module name to call module_setting_form()'
      )
    ),
    'unique keys' => array(
      'modulename' => array('modulename')
    )
  );

  return $schema;
}

/**
 * Creates a view showing the link between an organism & it's analysis through associated features.
 *
 * @ingroup tripal_analysis
 */
function tripal_analysis_add_mview_analysis_organism() {
  $view_name = 'analysis_organism';
  $comment = t('This view is for associating an organism (via it\'s associated features) to an analysis.');

  // this is the SQL used to identify the organism to which an analsysis
  // has been used.  This is obtained though the analysisfeature -> feature -> organism
  // joins
  $sql = "
    SELECT DISTINCT A.analysis_id, O.organism_id
    FROM analysis A
      INNER JOIN analysisfeature AF ON A.analysis_id = AF.analysis_id
      INNER JOIN feature F          ON AF.feature_id = F.feature_id
      INNER JOIN organism O         ON O.organism_id = F.organism_id
  ";

  // the schema array for describing this view
  $schema = array(
    'table' => $view_name,
    'description' => $comment,
    'fields' => array(
      'analysis_id' => array(
        'size' => 'big',
        'type' => 'int',
        'not null' => TRUE,
      ),
      'organism_id' => array(
        'size' => 'big',
        'type' => 'int',
        'not null' => TRUE,
      ),
    ),
    'indexes' => array(
      'networkmod_qtl_indx0' => array('analysis_id'),
      'networkmod_qtl_indx1' => array('organism_id'),
    ),
    'foreign keys' => array(
      'analysis' => array(
        'table' => 'analysis',
        'columns' => array(
          'analysis_id' => 'analysis_id',
        ),
      ),
      'organism' => array(
        'table' => 'organism',
        'columns' => array(
          'organism_id' => 'organism_id',
        ),
      ),
    ),
  );

  // add the view
  tripal_add_mview($view_name, 'tripal_analysis', $schema, $sql, $comment);
}