<?php

/**
 * @file
 * Contains functions executed only on install/uninstall of this module
 */

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

  // Disable all default views provided by this module
  require_once("tripal_cv.views_default.inc");
  $views = tripal_cv_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_cv
 */
function tripal_cv_requirements($phase) {
  $requirements = array();
  if ($phase == 'install') {
    // make sure chado is installed
    if (!$GLOBALS["chado_is_installed"]) {
      $requirements ['tripal_cv'] = array(
        'title' => "tripal_cv",
        'value' => "ERROR: Chado must be installed before this module can be enabled",
        'severity' => REQUIREMENT_ERROR,
      );
    }
  }
  return $requirements;
}

/**
 * Implementation of hook_install().
 *
 * @ingroup tripal_cv
 */
function tripal_cv_install() {

  // add the cv_root_mview
  tripal_cv_add_cv_root_mview();

  // add defaults to the tables that correlate OBO files/references with a chado CV
  tripal_cv_add_obo_defaults();

  // create the temp table we will use for loading OBO files
  tripal_cv_create_tripal_obo_temp();
}

/**
 * Implementation of hook_uninstall().
 *
 * @ingroup tripal_cv
 */
function tripal_cv_uninstall() {

  // drop the tripal_obo_temp table
  if (db_table_exists('chado.tripal_obo_temp')) {
    $sql = "DROP TABLE chado.tripal_obo_temp";
    db_query($sql);
  }
}

/**
 * Creates a temporary table to store obo details while loading an obo file
 *
 * @ingroup tripal_cv
 */
function tripal_cv_create_tripal_obo_temp() {
  // the tripal_obo_temp table is used for temporary housing of records when loading OBO files
  // we create it here using plain SQL because we want it to be in the chado schema but we
  // do not want to use the Tripal Custom Table API because we don't want it to appear in the
  // list of custom tables.  It needs to be available for the Tripal Chado API so we create it
  // here and then define it in the tripal_cv/api/tripal_cv.schema.api.inc
  if (!db_table_exists('chado.tripal_obo_temp')) {
    $sql = "
      CREATE TABLE {tripal_obo_temp} (
        id character varying(255) NOT NULL,
        stanza text NOT NULL,
        type character varying(50) NOT NULL,
        CONSTRAINT tripal_obo_temp_uq0 UNIQUE (id)
      );
    ";
    chado_query($sql);
    $sql = "CREATE INDEX tripal_obo_temp_idx0 ON {tripal_obo_temp} USING btree (id)";
    chado_query($sql);
    $sql = "CREATE INDEX tripal_obo_temp_idx1 ON {tripal_obo_temp} USING btree (type)";
    chado_query($sql);
  }
}

/**
 * Implementation of hook_schema().
 *
 * @ingroup tripal_cv
 */
function tripal_cv_schema() {
  $schema = array();

  tripal_cv_get_tripal_cv_obo_table($schema);
  tripal_cv_get_tripal_cv_defaults_table($schema);

  return $schema;
}
/**
 * Table definition for the tripal_cv_obo table
 * @param $schema
 */
function tripal_cv_get_tripal_cv_obo_table(&$schema) {
  $schema['tripal_cv_obo'] = array(
    'fields' => array(
      'obo_id' => array(
        'type' => 'serial',
        'unsigned' => TRUE,
        'not null' => TRUE
      ),
      'name' => array(
        'type' => 'varchar',
         'length' => 255
       ),
      'path'  => array(
        'type' => 'varchar',
        'length' => 1024
      ),
    ),
    'indexes' => array(
      'tripal_cv_obo_idx1' => array('obo_id'),
    ),
    'primary key' => array('obo_id'),
  );
}

/**
 * * Table definition for the tripal_cv_defaults table
 * @param unknown $schema
 */
function tripal_cv_get_tripal_cv_defaults_table(&$schema) {
  $schema['tripal_cv_defaults'] = array(
    'fields' => array(
      'cv_default_id' => array(
        'type' => 'serial',
        'unsigned' => TRUE,
        'not null' => TRUE
      ),
      'table_name' => array(
        'type' => 'varchar',
        'length' => 128,
        'not null' => TRUE,
      ),
      'field_name' => array(
        'type' => 'varchar',
        'length' => 128,
        'not null' => TRUE,
      ),
      'cv_id' => array(
        'type' => 'int',
        'not null' => TRUE,
      )
    ),
    'indexes' => array(
      'tripal_cv_defaults_idx1' => array('table_name', 'field_name'),
    ),
    'unique keys' => array(
      'tripal_cv_defaults_unq1' => array('table_name', 'field_name', 'cv_id'),
    ),
    'primary key' => array('cv_default_id')
  );
}

/**
 * Add a materialized view of root terms for all chado cvs. This is needed for viewing cv trees
 *
 * @ingroup tripal_cv
 */
function tripal_cv_add_cv_root_mview() {
  $mv_name = 'cv_root_mview';
  $comment = 'A list of the root terms for all controlled vocabularies. This is needed for viewing CV trees';
  $schema = array(
    'table' => $mv_name,
    'description' => $comment,
    'fields' => array(
      'name' => array(
        'type' => 'varchar',
        'length' => 255,
        'not null' => TRUE,
      ),
      'cvterm_id' => array(
        'type' => 'int',
        'not null' => TRUE,
      ),
      'cv_id' => array(
        'type' => 'int',
        'not null' => TRUE,
      ),
      'cv_name' => array(
        'type' => 'varchar',
        'length' => 255,
        'not null' => TRUE,
      ),
    ),
    'indexes' => array(
      'cv_root_mview_indx1' => array('cvterm_id'),
      'cv_root_mview_indx2' => array('cv_id'),
    ),
  );

  $sql = "
    SELECT DISTINCT CVT.name,CVT.cvterm_id, CV.cv_id, CV.name
    FROM cvterm_relationship CVTR
      INNER JOIN cvterm CVT on CVTR.object_id = CVT.cvterm_id
      INNER JOIN cv CV on CV.cv_id = CVT.cv_id
    WHERE CVTR.object_id not in
      (SELECT subject_id FROM cvterm_relationship)
  ";

  // Create the MView
  tripal_add_mview($mv_name, 'tripal_cv', $schema, $sql, $comment);
}

/**
 * Add's defaults to the tripal_cv_obo table
 *
 * @ingroup tripal_cv
 */
function tripal_cv_add_obo_defaults() {

  // insert commonly used ontologies into the tables
  $ontologies = array(
    array('Chado Feature Properties', drupal_get_path('module', 'tripal_cv') . '/feature_property.obo'),
    array('Relationship Ontology', 'http://www.obofoundry.org/ro/ro.obo'),
    array('Sequence Ontology', 'http://song.cvs.sourceforge.net/*checkout*/song/ontology/so.obo'),
    array('Gene Ontology', 'http://www.geneontology.org/ontology/gene_ontology.obo'),
    array('Cell Ontology', 'http://obo.cvs.sourceforge.net/obo/obo/ontology/anatomy/cell_type/cell.obo?rev=HEAD'),
    array('Plant Structure Ontology', 'http://palea.cgrb.oregonstate.edu/viewsvn/Poc/trunk/ontology/OBO_format/po_anatomy.obo?view=co'),
    array('Plant Growth and Development Stages Ontology', 'http://palea.cgrb.oregonstate.edu/viewsvn/Poc/trunk/ontology/OBO_format/po_temporal.obo?view=co')
  );
  foreach ($ontologies as $o) {
    db_query("INSERT INTO {tripal_cv_obo} (name,path) VALUES (:name, :path)", array(':name' => $o[0], ':path' => $o[1]));
  }
}


/**
 * This is the required update for tripal_cv when upgrading from Drupal core API 6.x.
 *
 */
function tripal_cv_update_7200() {

  // add in the new tripal_cv_defaults table
  try {
    $schema = array();
    tripal_cv_get_tripal_cv_defaults_table($schema);
    db_create_table('tripal_cv_defaults', $schema['tripal_cv_defaults']);
  }
  catch (\PDOException $e) {
    $error = $e->getMessage();
    throw new DrupalUpdateException('Failed to create tripal_cv_defaults table: '. $error);
  }
}

/**
 * Fixes an error with the materialized view installation
 *
 */
function tripal_cv_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 = 'cv_root_mview';
  $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();
  }
}