<?php
/**
 * @file
 * Installation of the publication module
 */

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

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

/**
 * Implementation of hook_install().
 *
 * @ingroup tripal_pub
 */
function tripal_pub_install() {
  global $base_path;

  // add loading of the the tripal pub ontology to the job queue
  $obo_path = '{tripal_pub}/files/tpub.obo';
  $obo_id = tripal_insert_obo('Tripal Publication', $obo_path);
  tripal_submit_obo_job(array('obo_id' => $obo_id));

  tripal_pub_add_cvs();
  tripal_pub_add_cvterms();

  // add the custom tables
  tripal_pub_add_custom_tables();

  // set the default vocabularies
  tripal_set_default_cv('pub', 'type_id', 'tripal_pub');
  tripal_set_default_cv('pubprop', 'type_id', 'tripal_pub');
  tripal_set_default_cv('pub_relationship', 'type_id', 'pub_relationship');

}

/**
 * Implementation of hook_uninstall().
 *
 * @ingroup tripal_pub
 */
function tripal_pub_uninstall() {

}

/**
 * Implements hook_enable().
 *
 * @ingroup tripal_pub
 */
function tripal_pub_enable() {

}

/**
 * Implementation of hook_schema().
 *
 * @ingroup tripal_pub
 */
function tripal_pub_schema() {

  $schema['chado_pub'] = 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
      ),
      'pub_id' => array(
        'type' => 'int',
        'not null' => TRUE,
        'default' => 0
      ),
      'sync_date' => array(
        'type' => 'int',
        'not null' => FALSE,
        'description' => 'UNIX integer sync date/time'
      ),
    ),
    'indexes' => array(
      'pub_id' => array('pub_id')
    ),
    'unique keys' => array(
      'nid_vid' => array('nid', 'vid'),
      'vid' => array('vid')
    ),
    'primary key' => array('nid'),
  );

  $schema['tripal_pub_import'] = array(
    'fields' => array(
      'pub_import_id' => array(
        'type' => 'serial',
        'not null' => TRUE
      ),
      'name' => array(
        'type' => 'varchar',
        'length' => 255,
        'not null' => TRUE
      ),
      'criteria' => array(
        'type' => 'text',
        'size' => 'normal',
        'not null' => TRUE,
        'description' => 'Contains a serialized PHP array containing the search criteria'
      ),
      'disabled'  => array(
        'type' => 'int',
        'unsigned' => TRUE,
        'not NULL' => TRUE,
        'default' => 0
      ),
      'do_contact'  => array(
        'type' => 'int',
        'unsigned' => TRUE,
        'not NULL' => TRUE,
        'default' => 0
      ),
    ),
    'primary key' => array('pub_import_id'),
    'indexes' => array(
      'name' => array('name')
    ),
  );

  return $schema;
}

/**
 * Add custom table related to publications
 *  - pubauthor_contact
 *
 * @ingroup tripal_pub
 */
// This function was moved to tripal_chado/includes/setup/tripal_chado.setup.inc
/* function tripal_pub_add_custom_tables() {
  $schema = array (
    'table' => 'pubauthor_contact',
    'fields' => array (
      'pubauthor_contact_id' => array (
        'type' => 'serial',
        'not null' => true,
      ),
      'contact_id' => array (
        'type' => 'int',
        'not null' => true,
      ),
      'pubauthor_id' => array (
        'type' => 'int',
        'not null' => true,
      ),
    ),
    'primary key' => array (
      0 => 'pubauthor_contact_id',
    ),
    'unique keys' => array (
      'pubauthor_contact_c1' => array (
        0 => 'contact_id',
        1 => 'pubauthor_id',
      ),
    ),
    'foreign keys' => array (
      'contact' => array (
        'table' => 'contact',
        'columns' => array (
          'contact_id' => 'contact_id',
        ),
      ),
      'pubauthor' => array (
        'table' => 'pubauthor',
        'columns' => array (
          'pubauthor_id' => 'pubauthor_id',
        ),
      ),
    ),
  );
  chado_create_custom_table('pubauthor_contact', $schema, TRUE);
} */

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


  // add the tripal_pub CV and set it to be the default for pub types and pub properties
  try {
    $cv_id = db_query("SELECT cv_id FROM chado.cv WHERE name = 'tripal_pub'")->fetchField();
    if (!$cv_id) {
      // add the vocabulary
      $cv_id = db_insert('chado.cv')
        ->fields(array(
          'name' => 'tripal_pub',
          'definition' => 'A heirarchical set of terms for describing a publication. It is intended to be used as the default vocabularies in Tripal for publication types and contact properties.'
        ))
        ->execute();
    }
    // use the new pub_property CV we just added
    db_insert('tripal_cv_defaults')
      ->fields(array(
        'table_name' => 'pub',
        'field_name' => 'type_id',
        'cv_id' => $cv_id
      ))
      ->execute();
    // use the new pub_property CV we just added
    db_insert('tripal_cv_defaults')
      ->fields(array(
        'table_name' => 'pubprop',
        'field_name' => 'type_id',
        'cv_id' => $cv_id
      ))
      ->execute();
  }
  catch (\PDOException $e) {
    $error = $e->getMessage();
    throw new DrupalUpdateException('Failed to add pub_property vocabulary: '. $error);
  }

  // add the pub_property CV
  try {
    $cv_id = db_query("SELECT cv_id FROM chado.cv WHERE name = 'pub_property'")->fetchField();
    if (!$cv_id) {
      // add the vocabulary
      $cv_id = db_insert('chado.cv')
        ->fields(array(
          'name' => 'pub_property',
          'definition' => 'Contains properties for publications. This can be used if the tripal_pub vocabulary (which is default for publications in Tripal) is not desired.'
        ))
        ->execute();
    }
  }
  catch (\PDOException $e) {
    $error = $e->getMessage();
    throw new DrupalUpdateException('Failed to add pub_property vocabulary: '. $error);
  }

  // add the pub_type CV
  try {
    $cv_id = db_query("SELECT cv_id FROM chado.cv WHERE name = 'pub_type'")->fetchField();
    if (!$cv_id) {
      // add the vocabulary
      $cv_id = db_insert('chado.cv')
      ->fields(array(
        'name' => 'pub_type',
        'definition' => 'Contains types of publications. This can be used if the tripal_pub vocabulary (which is default for publications in Tripal) is not desired.'
      ))
      ->execute();
    }
  }
  catch (\PDOException $e) {
    $error = $e->getMessage();
    throw new DrupalUpdateException('Failed to add pub_type vocabulary: '. $error);
  }

  // add the pub_relationship CV
  try {
    $cv_id = db_query("SELECT cv_id FROM chado.cv WHERE name = 'pub_relationship'")->fetchField();
    if (!$cv_id) {
      // add the vocabulary
      $cv_id = db_insert('chado.cv')
      ->fields(array(
        'name' => 'pub_relationship',
        'definition' => 'Contains types of relationships between publications.'
      ))
      ->execute();
    }
    // use the new pub_property CV we just added
    db_insert('tripal_cv_defaults')
      ->fields(array(
        'table_name' => 'pub_relationship',
        'field_name' => 'type_id',
        'cv_id' => $cv_id
      ))
      ->execute();
  }
  catch (\PDOException $e) {
    $error = $e->getMessage();
    throw new DrupalUpdateException('Failed to add pub_relationship vocabulary: '. $error);
  }
}

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

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

  return $dependencies;
}

/**
 * Adds missing foreign key constraints
 *
 */
function tripal_pub_update_7201() {
  // there was a bug in the function for creating a custom table that
  // kept foreign key constraints from being added.  So, we need to add those
  // to keep from error messages appear, we will drop the FK if it already
  // exists and then re-add it.
  try {
    $fkey_exists = db_query('SELECT TRUE FROM pg_constraint WHERE conname = :constraint', array(':constraint' => 'pubauthor_contact_pubauthor_id_fkey'))->fetchField();
    if ($fkey_exists) {
      db_query('
        ALTER TABLE chado.pubauthor_contact
        DROP CONSTRAINT pubauthor_contact_pubauthor_id_fkey CASCADE
      ');
      db_query('
        ALTER TABLE chado.pubauthor_contact
        DROP CONSTRAINT pubauthor_contact_contact_id_fkey CASCADE
      ');
    }
    db_query('
      ALTER TABLE chado.pubauthor_contact
      ADD CONSTRAINT pubauthor_contact_pubauthor_id_fkey
      FOREIGN KEY (pubauthor_id) REFERENCES chado.pubauthor (pubauthor_id)
      ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED
    ');
    db_query('
      ALTER TABLE chado.pubauthor_contact
      ADD CONSTRAINT pubauthor_contact_contact_id_fkey
      FOREIGN KEY (contact_id) REFERENCES chado.contact (contact_id)
      ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED
    ');
  }
  catch (\PDOException $e) {
    $error = $e->getMessage();
    throw new DrupalUpdateException('Failed to update foriegn key: '. $error);
  }
}
/**
 * Updates path of tripal_pub OBO to be relative.
 */
function tripal_pub_update_7202() {
  try {
    // Remove duplicates.
    db_delete('tripal_cv_obo')
      ->condition('name', 'Tripal Publication')
      ->execute();

    // Add in the updated path.
    $obo_path = '{tripal_pub}/files/tpub.obo';
    $obo_id = tripal_insert_obo('Tripal Publication', $obo_path);
  }
  catch (\PDOException $e) {
    $error = $e->getMessage();
    throw new DrupalUpdateException('Failed to update tripal_pub OBO path: '. $error);
  }
}