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

/**
 * Disable default views when module is disabled
 */
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_views_admin_disable_view($view_name,FALSE,array('suppress_error' => TRUE));
  }

}

/**
 * Implementation of hook_requirements().
 */
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().
 */
function tripal_analysis_install() {

  // create the module's data directory
  tripal_create_moddir('tripal_analysis');

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

  // add cvterms
  tripal_analysis_add_cvterms();

  // add materialized views
  tripal_analysis_add_mview_analysis_organism();
}

/**
 * Implementation of hook_uninstall().
 */
function tripal_analysis_uninstall() {

  // remove the materialized view
  if ($mview = tripal_mviews_get_mview_id('analysis_organism')) {
    tripal_mviews_action('delete', $mview);
  }
}
/**
 * 
 */
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);
  }
}
/*
 *
 */
function tripal_analysis_add_cvterms() {

  tripal_cv_add_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
  $term = array(
    'name' => 'analysis_date',
    'def' => 'The date that an analysis was performed.'
  );
  tripal_cv_add_cvterm($term, 'tripal', 0, 1, 'tripal');

  // 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
  $term = array(
    'name' => 'analysis_short_name',
    'def' => 'A computer legible (no spaces or special characters) abbreviation for the analysis.'
  );
  tripal_cv_add_cvterm($term, 'tripal', 0, 1 , 'tripal');


  // the 'analysis_property' vocabulary is for user definable properties.
  tripal_cv_add_cvterm(array('name' => 'Analysis Type', 'def' => 'The type of analysis that was performed.'),
     'analysis_property', 0, 1, 'tripal');
}

/**
 * Implementation of hook_schema() creates two tables.
 *
 * - 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.
 */
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;
}

/*
 *
 * @ingroup tripal_network
 */
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(
        'type' => 'int',
        'not null' => TRUE,
      ),
      'organism_id' => array(
        '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);
}