<?php

/**
 * Add body classes if certain regions have content.
 */
function abims_preprocess_html(&$variables) {
  if (!empty($variables['page']['featured'])) {
    $variables['classes_array'][] = 'featured';
  }

  if (!empty($variables['page']['triptych_first'])
    || !empty($variables['page']['triptych_middle'])
    || !empty($variables['page']['triptych_last'])) {
    $variables['classes_array'][] = 'triptych';
  }

  if (!empty($variables['page']['footer_firstcolumn'])
    || !empty($variables['page']['footer_secondcolumn'])
    || !empty($variables['page']['footer_thirdcolumn'])
    || !empty($variables['page']['footer_fourthcolumn'])) {
    $variables['classes_array'][] = 'footer-columns';
  }

  // Add conditional stylesheets for IE
  drupal_add_css(path_to_theme() . '/css/ie.css', array('group' => CSS_THEME, 'browsers' => array('IE' => 'lte IE 7', '!IE' => FALSE), 'preprocess' => FALSE));
  drupal_add_css(path_to_theme() . '/css/ie6.css', array('group' => CSS_THEME, 'browsers' => array('IE' => 'IE 6', '!IE' => FALSE), 'preprocess' => FALSE));
  if ( preg_match('/rhodoexplorer/', getenv('DATABASE')) ) {
    drupal_add_css('.site-footer {background-color: #d28a78;}', array('group' => CSS_THEME, 'type' => 'inline', 'weight' => '9999'));
    drupal_add_css('.navbar {background-color: #d28a78;}', array('group' => CSS_THEME, 'type' => 'inline', 'weight' => '9999'));
  }

  if (drupal_is_front_page()) {
    $variables['head_title_array']['title'] = "";
    $variables['head_title'] = $variables['head_title_array']['name'];
  }
}

/**
 * Override or insert variables into the page template for HTML output.
 */
function abims_process_html(&$variables) {
  // Hook into color.module.
  if (module_exists('color')) {
    _color_html_alter($variables);
  }
}

/**
 * Override or insert variables into the page template.
 */
function abims_process_page(&$variables) {

  // Move user login to footer
  //$variables['page']['footer'][] = $variables['page']['sidebar_first']['user_login'];
  unset($variables['page']['sidebar_first']['user_login']);
  unset($variables['page']['footer']['system_powered-by']);

  // Hook into color.module.
  if (module_exists('color')) {
    _color_page_alter($variables);
  }
  // Always print the site name and slogan, but if they are toggled off, we'll
  // just hide them visually.
  $variables['hide_site_name']   = theme_get_setting('toggle_name') ? FALSE : TRUE;
  $variables['hide_site_slogan'] = theme_get_setting('toggle_slogan') ? FALSE : TRUE;
  if ($variables['hide_site_name']) {
    // If toggle_name is FALSE, the site_name will be empty, so we rebuild it.
    $variables['site_name'] = filter_xss_admin(variable_get('site_name', 'Drupal'));
  }
  if ($variables['hide_site_slogan']) {
    // If toggle_site_slogan is FALSE, the site_slogan will be empty, so we rebuild it.
    $variables['site_slogan'] = filter_xss_admin(variable_get('site_slogan', ''));
  }
  // Since the title and the shortcut link are both block level elements,
  // positioning them next to each other is much simpler with a wrapper div.
  if (!empty($variables['title_suffix']['add_or_remove_shortcut']) && $variables['title']) {
    // Add a wrapper div using the title_prefix and title_suffix render elements.
    $variables['title_prefix']['shortcut_wrapper'] = array(
      '#markup' => '<div class="shortcut-wrapper clearfix">',
      '#weight' => 100,
    );
    $variables['title_suffix']['shortcut_wrapper'] = array(
      '#markup' => '</div>',
      '#weight' => -99,
    );
    // Make sure the shortcut link is the first item in title_suffix.
    $variables['title_suffix']['add_or_remove_shortcut']['#weight'] = -100;
  }

  // Simplify node title for mRNA and proteins
  if (array_key_exists('node', $variables) && $variables['node']->type == 'chado_feature' && ($variables['node']->feature->type_id->name == 'polypeptide' || $variables['node']->feature->type_id->name == 'mRNA')) {
      $variables['title'] = substr(strstr($variables['title'], ', '), 2);
      drupal_set_title($variables['title']);
  }

  if ($variables['is_front']) {
    $variables['page']['analyses'] = abims_get_analyses_from_chado();
  }
  $variables['page']['organisms'] = abims_get_organisms_with_versions_from_chado();
}

function abims_get_analyses_from_chado() {
  $analysis_list = array();

  $sql = 'SELECT cvterm_id FROM {cvterm} WHERE name = :name order by cvterm_id';
  $gene_term = chado_query($sql, array(':name' => 'gene'))->fetchField();

  $sql = 'SELECT cvterm_id FROM {cvterm} WHERE name = :name order by cvterm_id';
  $mRNA_term = chado_query($sql, array(':name' => 'mRNA'))->fetchField();

  // use this SQL statement for getting the analyses
  $csql =  "SELECT a.*, count(af.feature_id) as feature_count FROM {analysis} a LEFT JOIN {analysisfeature} af ON a.analysis_id = af.analysis_id GROUP BY a.analysis_id ORDER BY a.name";
  $analyses = chado_query($csql);

  $structural_ids = array();

  // iterate through the analyses and build an array of those that are synced
  foreach ($analyses as $an) {
    if (preg_match('/blast2GO/i', $an->name) || preg_match('/interpro/i', $an->name) || preg_match('/blast/i', $an->name) || preg_match('/diamond/i', $an->name) || preg_match('/trinotate/i', $an->name)) {
        $an->human_kind = 'functional';
    }
    else if (preg_match('/annotation/i', $an->name) || preg_match('/ogs/i', $an->name) || preg_match('/prediction/i', $an->name)) {
        $an->human_kind = 'structural';
        $structural_ids[] = $an->analysis_id;
    }
    else if (preg_match('/transcriptome/i', $an->name)) {
        $an->human_kind = 'transcriptome';
    }
    else if (preg_match('/assembly/i', $an->name) || preg_match('/genome/i', $an->name)) {
        $an->human_kind = 'assembly';
    }
    else {
        $an->human_kind = 'unknown';
    }

    // Guess a version number
    if (preg_match('/.*\s\(?(OGS\s?[0-9.]+)\)?\b.*/i', $an->name, $m) && count($m) == 2) {
      $an->guessed_version = str_replace(' ', '', $m[1]);
    }
    else if (preg_match('/.*\s\(?v([0-9.]+)\)?\b.*/i', $an->name, $m) && count($m) == 2) {
      $an->guessed_version = str_replace(' ', '', $m[1]);
    }
    else if (preg_match('/.*\s\(?v?([0-9.]+)\)?\b.*/i', $an->name, $m) && count($m) == 2) {
      $an->guessed_version = str_replace(' ', '', $m[1]);
    }
    else if (preg_match('/.*\s\(?(TR2012b)\)?\b.*/i', $an->name, $m) && count($m) == 2) {
      // Hard coded for spodoptera frugiperda
      $an->guessed_version = str_replace(' ', '', $m[1]);
    }

    if (preg_match('/.*\sclone\s+[A-Za-z0-9]+\b.*/i', $an->name, $m) && count($m) == 2) {
      $an->guessed_version += $m[1];
    }

    $analysis_list[$an->analysis_id] = $an;
  }

  $csql = "SELECT af.analysis_id, f.organism_id as organism_id FROM {analysisfeature} af, {feature} f WHERE af.feature_id = f.feature_id GROUP BY af.analysis_id, f.organism_id";
  $analyses = chado_query($csql);
  foreach ($analyses as $analysis) {
    $analysis_list[$analysis->analysis_id]->organism_id[] = $analysis->organism_id;
  }

  // Fix feature_counts for structural annots
  $csql = "SELECT a.analysis_id, count(af.feature_id) as feature_count FROM {analysis} a LEFT JOIN {analysisfeature} af ON a.analysis_id = af.analysis_id LEFT JOIN {feature} f ON af.feature_id = f.feature_id WHERE f.type_id=:term GROUP BY a.analysis_id ORDER BY a.name";
  $counts = chado_query($csql, array(':term' => $gene_term));
  if (!$counts->rowCount()) {
    $counts = chado_query($csql, array(':term' => $mRNA_term));
  }
  foreach ($counts as $count) {
    if (in_array($count->analysis_id, $structural_ids)) {
      $analysis_list[$count->analysis_id]->feature_count = $count->feature_count;
    }
  }

  // Classify by organism
  $an_by_orgs = [];
  $multi = [];
  $none = [];
  foreach ($analysis_list as $an_id => $an) {
    if (count($an->organism_id) == 1) {
      $an_by_orgs[$an->organism_id[0]][$an_id] = $an;
    }
    else if (count($an->organism_id) > 1) {
      $multi[$an_id] = $an;
    }
    else {
      $none[$an_id] = $an;
    }
  }

  // Classify by guessed version
  foreach ($an_by_orgs as $org_id => $ans) {
    foreach ($ans as $an_id => $an) {
      if ($an->human_kind == 'functional') {
        $adopted = False;
        foreach ($ans as $an_id2 => $an2) {
          if (($an2->human_kind == 'structural' || $an2->human_kind == 'transcriptome') && $an->guessed_version == $an2->guessed_version) {
            $an2->children[$an_id] = $an;
            $ans[$an_id2] = $an2;
            $adopted = True;
            break;
          }
        }
        if ($adopted) {
          unset($ans[$an_id]);
        }
      }
    }
    $an_by_orgs[$org_id] = $ans;
  }

  // Find parent genome of each structural annot
  $struct_to_assembly = array();
  foreach ($structural_ids as $key => $strut_id) {
    $csql =  "SELECT aft.analysis_id as target_id FROM {featureloc} fl, {feature} ft, {analysisfeature} aft WHERE fl.srcfeature_id = ft.feature_id AND ft.feature_id = aft.feature_id AND fl.feature_id in (select af.feature_id from {analysisfeature} af, {feature} f where af.feature_id = f.feature_id and f.type_id = :gene_term and af.analysis_id = :an_id limit 1) limit 1;";
    $target_analysis = chado_query($csql, array(':gene_term' => $gene_term, ':an_id' => $strut_id))->fetchField();
    $struct_to_assembly[$strut_id] = $target_analysis;
  }

  foreach ($an_by_orgs as $org_id => $ans) {
    foreach ($ans as $an_id => $an) {
      if ($an->human_kind == 'structural' || $an->human_kind == 'transcriptome') {
        $adopted = False;
        foreach ($ans as $an_id2 => $an2) {
          if ($an2->human_kind == 'assembly' && $an_id2 == $struct_to_assembly[$an_id]) {
            $an2->children[$an_id] = $an;
            $ans[$an_id2] = $an2;
            $adopted = True;
            break;
          }
        }
        if ($adopted) {
          unset($ans[$an_id]);
        }
      }
    }
    $an_by_orgs[$org_id] = $ans;
  }

  if (!empty($multi))
    $an_by_orgs['multi'] = $multi;
  if (!empty($none))
    $an_by_orgs['none'] = $none;

  return $an_by_orgs;
}

function abims_get_organisms_from_chado() {
  $organism_list = array();
  // use this SQL statement for getting the analyses
  $csql =  "SELECT * FROM {organism} ORDER BY genus, species";
  $organisms = chado_query($csql);

  // iterate through the organisms and build an array of them
  foreach ($organisms as $organism) {
    $organism_list[$organism->organism_id] = $organism;
  }

  return $organism_list;
}

function abims_get_organisms_with_versions_from_chado() {
  $organism_list = array();

  $csql =  "SELECT * FROM {organism} ORDER BY genus, species";
  $organisms = chado_query($csql);

  $csql =  "SELECT name FROM {analysis} order by analysis_id desc";
  $analyses = chado_query($csql);

  $versions = array();
  foreach ($analyses as $an) {
    if ((preg_match('/assembly/i', $an->name) || preg_match('/genome/i', $an->name)) && !preg_match('/transcriptome/i', $an->name)) {
      if (preg_match('/([A-Za-z0-9]+ [A-Za-z0-9]+).+v\.?([0-9.]+)/', $an->name, $matches)) {
        if (!array_key_exists($matches[1], $versions) || version_compare($matches[2], $versions[$matches[1]], '>')) {
          $versions[$matches[1]] = $matches[2];
        }
      }
      if (preg_match('/([A-Za-z0-9]+ [A-Za-z0-9]+ [A-Za-z0-9]+).+v\.?([0-9.]+)/', $an->name, $matches)) {
        if (!array_key_exists($matches[1], $versions) || version_compare($matches[2], $versions[$matches[1]], '>')) {
          $versions[$matches[1]] = $matches[2];
        }
      }
      if (preg_match('/v\.?([0-9.]+).+ ([A-Za-z0-9]+ [A-Za-z0-9]+ [A-Za-z0-9]+)$/', $an->name, $matches)) {
        if (!array_key_exists($matches[2], $versions) || version_compare($matches[1], $versions[$matches[2]], '>')) {
          $versions[$matches[2]] = $matches[1];
        }
      }
      if (preg_match('/v\.?([0-9.]+).+ ([A-Za-z0-9]+ [A-Za-z0-9]+)$/', $an->name, $matches)) {
        if (!array_key_exists($matches[2], $versions) || version_compare($matches[1], $versions[$matches[2]], '>')) {
          $versions[$matches[2]] = $matches[1];
        }
      }
    }
  }

  foreach ($organisms as $organism) {
    if (array_key_exists($organism->genus . ' ' . $organism->species, $versions)) {
        $organism->version = $versions[$organism->genus . ' ' . $organism->species];
      }
    $organism_list[$organism->organism_id] = $organism;
  }

  return $organism_list;
}

/**
 * Implements hook_preprocess_maintenance_page().
 */
function abims_preprocess_maintenance_page(&$variables) {
  // By default, site_name is set to Drupal if no db connection is available
  // or during site installation. Setting site_name to an empty string makes
  // the site and update pages look cleaner.
  // @see template_preprocess_maintenance_page
  if (!$variables['db_is_active']) {
    $variables['site_name'] = '';
  }
  drupal_add_css(drupal_get_path('theme', 'abims') . '/css/maintenance-page.css');
}

/**
 * Override or insert variables into the maintenance page template.
 */
function abims_process_maintenance_page(&$variables) {
  // Always print the site name and slogan, but if they are toggled off, we'll
  // just hide them visually.
  $variables['hide_site_name']   = theme_get_setting('toggle_name') ? FALSE : TRUE;
  $variables['hide_site_slogan'] = theme_get_setting('toggle_slogan') ? FALSE : TRUE;
  if ($variables['hide_site_name']) {
    // If toggle_name is FALSE, the site_name will be empty, so we rebuild it.
    $variables['site_name'] = filter_xss_admin(variable_get('site_name', 'Drupal'));
  }
  if ($variables['hide_site_slogan']) {
    // If toggle_site_slogan is FALSE, the site_slogan will be empty, so we rebuild it.
    $variables['site_slogan'] = filter_xss_admin(variable_get('site_slogan', ''));
  }
}

/**
 * Override or insert variables into the node template.
 */
function abims_preprocess_node(&$variables) {
  if ($variables['view_mode'] == 'full' && node_is_page($variables['node'])) {
    $variables['classes_array'][] = 'node-full';
  }

  unset($variables['content']['links']['node']['#links']['node-readmore']);

  unset($variables['content']['links']['comment']['#links']);
}

/**
 * Override or insert variables into the block template.
 */
function abims_preprocess_block(&$variables) {
    // In the header region visually hide block titles.
    if ($variables['block']->region == 'header') {
        $variables['title_attributes_array']['class'][] = 'element-invisible';
    }

    if ($variables['block']->module == 'user' && $variables['block']->delta == 'login') {
        $variables['block']->region = 'footer';
    }
}

/**
 * Implements theme_menu_tree().
 */
function abims_menu_tree($variables) {
  return '<ul class="menu clearfix">' . $variables['tree'] . '</ul>';
}

/**
 * Implements theme_field__field_type().
 */
function abims_field__taxonomy_term_reference($variables) {
  $output = '';

  // Render the label, if it's not hidden.
  if (!$variables['label_hidden']) {
    $output .= '<h3 class="field-label">' . $variables['label'] . ': </h3>';
  }

  // Render the items.
  $output .= ($variables['element']['#label_display'] == 'inline') ? '<ul class="links inline">' : '<ul class="links">';
  foreach ($variables['items'] as $delta => $item) {
    $output .= '<li class="taxonomy-term-reference-' . $delta . '"' . $variables['item_attributes'][$delta] . '>' . drupal_render($item) . '</li>';
  }
  $output .= '</ul>';

  // Render the top-level DIV.
  $output = '<div class="' . $variables['classes'] . (!in_array('clearfix', $variables['classes_array']) ? ' clearfix' : '') . '"' . $variables['attributes'] .'>' . $output . '</div>';

  return $output;
}

function abims_theme($existing, $type, $theme, $path) {
    $items['website_search_box_form'] = array(
        'render element' => 'form',
        'template' => 'website_search_box_form',
        'path' => drupal_get_path('theme', 'abims') . '/templates/form',
    );

  $items['tripal_orthology_links'] = array(
    'variables' => array('node' => NULL),
    'template' => 'tripal_orthology_links',
    'path' =>  drupal_get_path('theme', 'abims') . '/templates',
    'theme path' => '',
    'type' => 'module',
    'preprocess functions' => array(),
    'process function' => '',
  );

  $items['tripal_aureme_links'] = array(
    'variables' => array('node' => NULL),
    'template' => 'tripal_aureme_links',
    'path' =>  drupal_get_path('theme', 'abims') . '/templates',
    'theme path' => '',
    'type' => 'module',
    'preprocess functions' => array(),
    'process function' => '',
  );

  $items['tripal_aphidcyc_links'] = array(
    'variables' => array('node' => NULL),
    'template' => 'tripal_aphidcyc_links',
    'path' =>  drupal_get_path('theme', 'abims') . '/templates',
    'theme path' => '',
    'type' => 'module',
    'preprocess functions' => array(),
    'process function' => '',
  );
    return $items;
}

/**
 * Override the theme registry.
 */
function abims_theme_registry_alter(&$theme_registry) {
  $theme_registry['tripal_orthology_links'] = array(
    'variables' => array('node' => NULL),
    'template' => 'tripal_orthology_links',
    'path' =>  drupal_get_path('theme', 'abims') . '/templates',
    'theme path' => '',
    'type' => 'module',
    'preprocess functions' => array(),
    'process function' => '',
  );

  $theme_registry['tripal_aureme_links'] = array(
    'variables' => array('node' => NULL),
    'template' => 'tripal_aureme_links',
    'path' =>  drupal_get_path('theme', 'abims') . '/templates',
    'theme path' => '',
    'type' => 'module',
    'preprocess functions' => array(),
    'process function' => '',
  );
}

function abims_node_view_alter(&$build) {
  if ($build['#bundle'] == 'chado_feature') {

    if ($build['#view_mode'] != 'full' || array_key_exists('tripal_orthology_links', $build)) {
      return;
    }

    if (getenv('ENABLE_ORTHOLOGY_LINKS')) {
      $build['tripal_orthology_links'] = array(
        '#theme' => 'tripal_orthology_links',
        '#node' => $build['#node'],
        '#tripal_toc_id' => 'orthology',
        '#tripal_toc_title' => 'Orthology',
      );
    }

    if (getenv('ENABLE_AUREME_LINKS') && !array_key_exists('tripal_aureme_links', $build)) {
        $build['tripal_aureme_links'] = array(
          '#theme' => 'tripal_aureme_links',
          '#node' => $build['#node'],
          '#tripal_toc_id' => 'aureme',
          '#tripal_toc_title' => 'Metabolic model',
        );
    }

    if (getenv('ENABLE_APHIDCYC') && !array_key_exists('tripal_aphidcyc_links', $build)) {
      $build['tripal_aphidcyc_links'] = array(
        '#theme' => 'tripal_aphidcyc_links',
        '#node' => $build['#node'],
        '#tripal_toc_id' => 'aphidcyc',
        '#tripal_toc_title' => 'Metabolic data',
      );
    }
  }
}

function abims_module_implements_alter(&$implementations, $hook) {
  if ($hook == "node_view_alter") {
    $implementations = array('abims' => FALSE) + $implementations;
  }
}

// Disable default favicon
function abims_html_head_alter(&$head_elements) {
  foreach ($head_elements as $key => $element) {
    if ( 0 === strpos($key, 'drupal_add_html_head_link:shortcut icon:')
         && !empty($element['#attributes']['href'])
         && 'shortcut icon' === $element['#attributes']['rel']) {
      unset($head_elements[$key]);
    }
  }
}

// Disable registration
function abims_form_alter(&$form, &$form_state, $form_id) {
  switch($form_id) {
    case 'user_register_form':
      $form['#access'] = FALSE;
    break;
  }
}

// By default, select only mRNA and polypeptide in feature listing
// Also, list analysis by default
function abims_views_default_views_alter(&$views) {
    $sql = 'SELECT cvterm_id FROM {cvterm} WHERE name = :name1 or name = :name2';
    $results = chado_query($sql, array(':name1' => 'mRNA', ':name2' => 'polypeptide'))->fetchAll();

    foreach ($results as $res) {
        $views['tripal_feature_user_feature']->display['default']->display_options['filters']['type_id']['value'][] = $res->cvterm_id;
    }

    $views['tripal_feature_user_feature']->display['default']->display_options['filters']['type_id']['expose']['select_multiple'] = TRUE;
    $views['tripal_feature_user_feature']->display['default']->display_options['filters']['common_name']['expose']['select_multiple'] = TRUE;

    $views['tripal_analysis_user_analyses']->display['default']->display_options['exposed_form']['type'] = 'basic';
}