<?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' => 'tripal'
    ),
    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' => 'tripal'
    ),
    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(
        '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);
}

/**
 * This is the required update for tripal_organism when upgrading from Drupal core API 6.x.
 *
 */
function tripal_analysis_update_7200() {
  // We cannot use the Tripal API calls in the 7200 update
  // because during upgrade the tripal_core should also be disabled

  // set the analysis_property as default
  try {
    $cv_id = db_query("SELECT cv_id FROM chado.cv WHERE name = 'analysis_property'")->fetchField();
    db_insert('tripal_cv_defaults')
      ->fields(array(
        'table_name' => 'analysisprop',
        'field_name' => 'type_id',
        'cv_id' => $cv_id
      ))
      ->execute();
  }
  catch (\PDOException $e) {
    $error = $e->getMessage();
    throw new DrupalUpdateException('Failed to add analysis_property vocabulary: '. $error);
  }


  // During the upgrade from D6 to D7 the vocabulary terms assigned to organisms were
  // copied to the field_data_taxonomyextra table rather than to the correct
  // field_data_taxonomy_vocabulary_[vid] table. We'll move them.
  $vid = db_query("SELECT vid FROM {taxonomy_vocabulary} WHERE name = 'Analysis'")->fetchField();
  if ($vid) {
    try {
      // first move from the field_data_taxonomyextra table
      $sql = "
        INSERT INTO {field_data_taxonomy_vocabulary_$vid}
          (entity_type, bundle, deleted, entity_id, revision_id, language, delta, taxonomy_vocabulary_" . $vid. "_tid)
        (SELECT entity_type, bundle, deleted, entity_id, revision_id, language, delta, taxonomyextra_tid
         FROM field_data_taxonomyextra
         WHERE bundle = 'chado_feature')
      ";
      db_query($sql);
      $sql = "DELETE FROM field_data_taxonomyextra WHERE bundle = 'chado_analysis'";
      db_query($sql);

      // next move from the field_revision_taxonomyextra table
      $sql = "
        INSERT INTO {field_revision_taxonomy_vocabulary_$vid}
          (entity_type, bundle, deleted, entity_id, revision_id, language, delta, taxonomy_vocabulary_" . $vid. "_tid)
        (SELECT entity_type, bundle, deleted, entity_id, revision_id, language, delta, taxonomyextra_tid
         FROM field_revision_taxonomyextra
         WHERE bundle = 'chado_feature')
      ";
      db_query($sql);
      $sql = "DELETE FROM field_revision_taxonomyextra WHERE bundle = 'chado_analysis'";
      db_query($sql);
    }
    catch (\PDOException $e) {
      $error = $e->getMessage();
      throw new DrupalUpdateException('Could not move organism taxonomy terms: '. $error);
    }
  }
}

/**
 * Implementation of hook_update_dependencies().  It specifies a list of
 * other modules whose updates must be run prior to this one.
 */
function tripal_analysis_update_dependencies() {
  $dependencies = array();

  // the tripal_cv update 7200 must run prior to update 7200 of this module
  $dependencies['tripal_analysis'][7200] = array(
    'tripal_cv' => 7200
  );

  return $dependencies;
}

/**
 * Fixes an error with the materialized view installation
 *
 */
function tripal_analysis_update_7201() {

  // there is a bug in the Tripal v2.0-alpha release that didn't add the
  // materialized view schema to the mviews table.
  // get the schema for the materialized view from the custom_tables table
  // as there is a copy there, but only if the schema is missing from the
  // materialized view table
  $view_name = 'analysis_organism';
  $schema = db_select('tripal_mviews', 'tm')
    ->fields('tm', array('mv_schema'))
    ->condition('name', $view_name)
    ->execute()
    ->fetchField();
  if (!$schema or $schema == 'Array') {
    $schema = db_select('tripal_custom_tables', 'tct')
      ->fields('tct', array('schema'))
      ->condition('table_name', $view_name)
      ->execute()
      ->fetchField();
    $schema_str = var_export(unserialize($schema), TRUE);
    $schema_str = preg_replace('/=>\s+\n\s+array/', '=> array', $schema_str);
    db_update('tripal_mviews')
      ->fields(array(
        'mv_schema' => $schema_str
      ))
      ->condition('name', $view_name)
      ->execute();
  }
}