#####################################################################
#!/usr/bin/perl -w
# Mode: perl
# Programmer: Kuan Chang
# Date: 12/05/2001
#####################################################################

use strict;
use lib '/export/share_more/ensembl/gramene_ensembl/perl/mutant/';

use DBI;
use CGI qw(:standard *table *TR *th *td *ul *ol);
use MuDB;
use GL qw(:DEFAULT);
use GramenePage;
use CSHL::Config;

#####################################################################
# constants
my $GO_PREFIX = "GO:";
my $TO_PREFIX = "TO:";
my $GR_PREFIX = "GR:";
my $EXE_NAME ="search_mutant";
my $ONTOLOGY_HOME ="/perl/ontology/";
my $MAP_HOME = "/maps/";
my $MAP_EXE_NAME = 'viewer';
my $ONTOLOGY_EXE_NAME = 'search_term';
my $SEARCH_PROTEIN_EXE_NAME ="protein_search";
my $CORNELL_RFLP_2001 = 1;
my $JRGP_2000 = 2;
my $RICE_MORPHOLOGICAL_MAP_2000 = 4;

#####################################################################
# Connect to the database
my $db = MuDB->new();
my $page = GramenePage->new(Apache->request);

my $input  = param('id');
my ($id, $is_GR);
undef $id;
($id, $is_GR) = extract_ID($input);

# create CGI object
my $cgi = new CGI;
print $cgi->header;

if(defined $id){

  my $name =  $db->get_mutant_name($id);
  my $symbol = $db->get_mutant_symbol($id);
  my $phenotypic_description =  $db->get_phenotypic_description($id);
  my $supplementray_description = $db->get_supplementray_description($id);
  my @reference_ids = $db->get_reference_ids('core_mutant', $id); 
  my @mutant_to_ontology_term_ids = $db->get_mutant_to_ontology($id);
  my @map_info_ids = $db->get_mutant_map_info_ids($id);

  #check if parameters are empty, set them undefined
  if(not $symbol){
    undef $symbol;
  }

  if(not $phenotypic_description){
    undef $phenotypic_description;
  }

  if(not $supplementray_description){
    undef $supplementray_description;
  }

  if(not @reference_ids){
    undef @reference_ids;
  }

  if(not @mutant_to_ontology_term_ids){
    undef @mutant_to_ontology_term_ids;
  }

  if(not @map_info_ids){
    undef @map_info_ids;
  }

  #####################################################################
  if($is_GR) {
    print $cgi->start_html(-title=>"Summary for Rice Mutant: $name ($input)", 
		         -style=>{'src'=>'/stylesheets/gramene.css'});
  }

  # show GramenePage header
  print header();
  print $page->start_body;
  # show Gramene search engine
  #print_search_area();
  print_mutant_search_area();

  # show mutant page
  if($is_GR) {
    print h1("Summary for Rice Mutant: <i>$name</i> ($input)");
    print start_table({-width=>'98%', -align=>'center', -cellpadding=>4, -cellspacing=>1});
    print TR(th({-align=>'left', -class=>'datatitle', -width=>'12%'}, 'Mutant Name'), td({-class=>'databody'}, $name));
    print TR(th({-align=>'left', -class=>'datatitle', -width=>'12%'}, 'Mutant Symbol'), td({-class=>'databody'}, $symbol));		
    print TR(th({-align=>'left', -class=>'datatitle', -width=>'20%'}, 'Phenotypic Description'), td({-class=>'databody'}, $phenotypic_description));

    # keep tables looking nice
    if(defined $supplementray_description){
      print TR(th({-align=>'left', -class=>'datatitle'}, 'Supplementray Description'));
      print TR(td({-align=>'left', -class=>'databody'}, $supplementray_description ||'No other information available'));
    }
    if(defined @mutant_to_ontology_term_ids){
      print end_table;
      print start_table({-width=>'98%', -align=>'center', -cellpadding=>4, -cellspacing=>1});
      print start_TR;
      if($#mutant_to_ontology_term_ids == 0){ 
	print th({-align=>'left', -class=>'datatitle', -width=>'23%'}, 'Associated Ontology Term');
      }
      else{
	print th({-align=>'left', -class=>'datatitle', -width=>'23%'}, 'Associated Ontology Terms');
      }
    
      my $term_count = 1;
      foreach my $ontology_id (@mutant_to_ontology_term_ids){
	my $ontology_term = $db->get_ontology_term_name($ontology_id);
	my $ontology_accession = $db->get_ontology_term_accession($ontology_id);
   
	print td({-class=>'databody'}, a({-href=>"$ONTOLOGY_HOME$ONTOLOGY_EXE_NAME?id=".$ontology_accession}, $term_count, ". ", $ontology_term));
      
	$term_count += 1;
      }
      print end_TR;
    }  

    if(defined @map_info_ids){
      print end_table;

      print start_table({-border=>1, -width=>'98%', -align=>'center', -cellpadding=>4, -cellspacing=>0});

      print TR(th({-align=>'left', -class=>'datatitle'}, 'Map Position'));
      print end_table;
      print start_table({-border=>1, -width=>'98%', -align=>'center', -cellpadding=>3, -cellspacing=>1});
      print TR(th({-align=>'center', -class=>'datatitle'}, ['#', 'Map Name', 'Chromosome Number', 'Start Position', 'Stop Position']));
    
      my $map_count = 1;
      my %seen;
      foreach my $map_info_id (@map_info_ids){
	if($map_count % 2 == 0) {
	  print start_TR({-class=>'databody', -align=>'center'});
	} else {
	  print start_TR({-align=>'center'}); 
	}
	my $map_type = $db->get_core_mutant_map_info("map_type", $map_info_id);
	my $chromosome_number = $db->get_core_mutant_map_info("chromosome_number", $map_info_id);
	my $map_id = get_map_id($map_type, $chromosome_number);
	my $start_position = $db->get_core_mutant_map_info("start_position", $map_info_id);
	my $end_position = $db->get_core_mutant_map_info("stop_position", $map_info_id);
	
	my $row = $map_id . $start_position . $end_position;
	my $map_link = "$MAP_HOME$MAP_EXE_NAME?reference_map_id=".$map_id;
	if($start_position ne ""){
	  $map_link .= "&start=$start_position";
	  if($end_position ne "") {
	    $map_link .= "&end=$end_position";
	  }
	}

	if(!$seen{$row}){
	  $seen{$row}++;
	 
	  print td($map_count);
	  print td({-align=>'left'}, a({-href=>"$map_link", -target=>"_blank"},  get_map_name($map_type)));
	  print td($chromosome_number);
	  print td($start_position);
	  print td($end_position);	   
       
	  $map_count += 1;
	  print end_TR;
	}
      }
      print end_TR;
    }

    if(defined @reference_ids){
      print end_table;

      print start_table({-border=>1, -width=>'98%', -align=>'center', -cellpadding=>4, -cellspacing=>1});

    print TR(th({-align=>'left', -class=>'datatitle'}, 'References'));
    print end_table;
    print start_table({-border=>1, -width=>'98%', -align=>'center', -cellpadding=>0, -cellspacing=>0});
    # print TR(th({-align=>'center', -class=>'datatitle'}, ['#', 'Title', 'Source', 'Author']));
    
    my $count=0;
    foreach my $reference_id (@reference_ids){
      if($count % 2 == 0) {
	print start_TR({-class=>'databody', -align=>'center'});
      } else {
	print start_TR({-align=>'center'}); 
      }
      
      #print td($count+1);
      my $ref_title =  $db->get_reference_info('title', $reference_id);
      my $ref_source = $db->get_reference_source($reference_id);
      my $ref_author = $db->get_reference_author($reference_id);
      my $ref_source_trivia = $db->get_reference_source_trivia($reference_id);
      my $index = $count + 1;

      print <<ITEM;
          <td align="LEFT">
            <dl>
              <dt>
                <table cellspacing="0" cellpadding="0">
                  <tr>
                    <td align="CENTER" valign="CENTER">
                      <img src="http://brie2.cshl.org:8082/images/icons/grain_icon.jpg" alt="grain_icon" height=16 width=16 align="center"></td><td align="CENTER" valign="CENTER"><span class="reftitle"><b>$index.<b></span>
                    </td>
                    <td align="LEFT" valign="CENTER">
                      <a class="gopage" href="/perl/pub_search?ref_id=$reference_id">$ref_author</a>
                    </td>
                  </tr>
                </table>
              </dt>
              <dd>
                <table cellspacing="0" cellpadding="0">
                  <tr><td><span class="reftitle">$ref_title.</span></td></tr>
                  <tr><span class="smallrefsize"><td>$ref_source. $ref_source_trivia</td></span></tr>
                </table>
              </dd>
            </dl>
          </td>
ITEM

     # print td({-align=>'left'}, $ref_title);
     # print td({-align=>'left'}, $ref_source);
     # print td(a({-align=>'left', -href=>"../pub_search?ref_id=".$reference_id}, $ref_author));
      $count += 1;
    }
  }
print end_table;
}
else{
  print_top("Cannot find any information about $input");
  print_mutant_search_area();
  print h1("Sorry! Cannot find any information about <i>$input</i>");
}

print $page->end_body;
}

# utility functions
sub extract_ID{
  my $id = shift;
  my $is_GR = 0;
  if($id =~ /$GR_PREFIX/) {
    $id =~ s/$GR_PREFIX//;
    $is_GR = 1;
  } 
  return ($id, $is_GR);
}

###
sub get_map_id {
  my ($map_type, $chromosome_number) = @_;
  die "Invalid input in get_map_id" unless defined $map_type; 
  die "Invalid input in get_map_id" unless defined $chromosome_number;
  
  my $dbh =  DBI->connect(MapDataSource, MapDBUser, MapDBPassword,   {
        'PrintError'  => 1, 
        'RaiseError'  => 1,
        'LongReadLen' => 3000,
        'LongTruncOk' => 1,
      }); 

  my $map_study_id;
  if($map_type == 1) {
    $map_study_id = $CORNELL_RFLP_2001;
  }
  elsif($map_type == 2){
    $map_study_id = $JRGP_2000;    
  }
  else{
    #$map_type == 3
    $map_study_id = $RICE_MORPHOLOGICAL_MAP_2000;
  }
  
  my $sth = $dbh->prepare("SELECT map_id FROM map WHERE map_study_id = $map_study_id AND linkage_group = '$chromosome_number'") || die $dbh->errstr;
  $sth->execute || die "Execute: ", $sth->errstr;
  my $map_id = $sth->fetchrow_array;
  $sth->finish;
  $dbh->disconnect();
  return $map_id;
}

#
sub get_map_name {
  my ($map_type) = @_;  
  if($map_type == 1) {
    return "Cornell Rice RFLP 2001";
  }
  elsif($map_type == 2){
    return "JRGP Rice 2000";    
  }
  else{
    #$map_type == 3
    return "Rice Morphological Map 2000";
  }
}
