#####################################################################
#!/usr/local/bin/perl -w
# Mode: perl
# Programmer: Kuan Chang
# Date: 04/22/2001
#####################################################################

use strict;

use POSIX('ceil');
use CGI qw(:standard *table *TR *th *td *ul *ol);
use Gramene::Mutant::MutantSearchDB;
use Gramene::Page;

#####################################################################
# constants

use constant GO_PREFIX => 'GO:';
use constant TO_PREFIX => 'TO:';
# GR_PREFIX is for mutant
use constant GR_PREFIX => 'GR:';
use constant STUDY_PREFIX => 'GR:ST:';
# my $GR_PREFIX = "GR:";

use constant EXE_NAME => 'search_mutant';
use constant ONTOLOGY_HOME => '/db/ontology/';
use constant ONTOLOGY_EXE_NAME => 'search_term';
use constant STUDY_EXE_NAME => 'search_study';
use constant SEARCH_PROTEIN_EXE_NAME => 'protein_search';
use constant MUTANT_IMAGE_HOME => '/images/mutant/';
use constant MAX_LENGTH_OF_ACCESSION => 7;
use constant CORNELL_RFLP_2001 => 3;
use constant JRGP_2000 => 6;
#this is for raclette 
use constant RICE_MORPHOLOGICAL_MAP_2000 => 8;

# my $CORNELL_RFLP_2001 = 1;
# my $JRGP_2000 = 2;
# my $RICE_MORPHOLOGICAL_MAP_2000 = 4;

#####################################################################
# Connect to the database
my $db = Gramene::Mutant::MutantSearchDB->new();
$db->connect_db(); 

my $page = Gramene::Page->new(Apache->request);

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

# if(is_digit($input)){
#  $id = $input;
#}

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

if(defined $id && $is_study){

  my $study =  $db->get_study($id);
  my $study_name = $db->get_study_name($id);
  my $study_year = $db->get_study_year($id);
  my $study_season = $db->get_study_season($id);
  my $study_location = $db->get_study_location($id);
  my $study_type = $db->get_study_type($id);
  my @study_to_mutants = $db->get_study_to_mutants($id);
  my $study_environment = $db->get_study_environment($id);
  my $reference_ids_ref = $db->get_reference_ids('gramene.gene.study', $id);

  #check if parameters are empty, set them undefined
  undef $study unless $study;
  undef $study_name unless $study_name;
  undef $study_year unless $study_year;
  undef $study_season unless $study_season;
  undef $study_location unless $study_location;
  undef $study_type unless $study_type;
  undef $study_environment unless $study_environment;
  undef @study_to_mutants unless @study_to_mutants;
 # undef @reference_ids unless @reference_ids;

#######################################################################
  if(defined $study) {
        print $page->start_html(-title=>"Study page"); 
  }
  else{
    print $page->start_html(-title=>"Cannot find any information about $input"); 
  }

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

  # show study page
  if(defined $study) {
    my @study_columns = split("\t", $study);
    if($study_name ne 'NA'){
      print h1("Study: <i>$study_name</i> ($input)");
    }else{
       print h1("Study: ($input)");
    }

    print start_table({-width=>'98%', -align=>'center', -cellpadding=>4, -cellspacing=>1});
   if($study_name ne 'NA'){
    print TR(th({-align=>'left', -class=>'datatitle', -width=>'20%'}, 'Study Name'), td({-colspan=>4, -class=>'databody'}, $study_name));
   }   
   
   $study_year ='NA' unless $study_year;
    print TR(th({-align=>'left', -class=>'datatitle', -width=>'20%'}, 'Year'), td({-colspan=>4, -class=>'databody'}, $study_year));		
    print TR(th({-align=>'left', -class=>'datatitle', -width=>'20%'}, 'Season'), td({-colspan=>4, -class=>'databody'}, $study_season));
    print TR(th({-align=>'left', -class=>'datatitle', -width=>'20%'}, 'Location'), td({-colspan=>4, -class=>'databody'}, $study_location));
    print TR(th({-align=>'left', -class=>'datatitle', -width=>'20%'}, 'Study Type'), td({-colspan=>4, -class=>'databody'}, $study_type));
   
####################################
  if(@study_to_mutants){
        my $total=@study_to_mutants;
        my $row=ceil($total/3);
        print start_TR;
        print th({-align=>'left', -class=>'datatitle', -width=>'20%',-rowspan=>$row}, 'Gene');
        my $i=0;
        for(;$i<$total && $i!=3;$i++){
           
           my $mutant_id=$study_to_mutants[$i];
           my $mutant_name = $db->get_mutant_name($mutant_id);
	   my $mutant_accession = get_canonical_accession(GR_PREFIX, $mutant_id);
           if($mutant_name eq 'NA'){
	      print td({-class=>'databody', -align=>'left'}, $i+1, '.', a({-target=>"mutant",-href=>EXE_NAME ."?id=$mutant_accession"}, $mutant_accession));
	   }else {
	     print td({-class=>'databody', -align=>'left'}, $i+1, '.', a({-target=>"mutant",-href=>EXE_NAME ."?id=$mutant_accession"}, $mutant_name));
            }
                     
         }
         print end_TR;
        
         for(;$i<$total;$i++){
            print start_TR if ($i%3==0);
                
            my $mutant_id=$study_to_mutants[$i];	
	    my $mutant_name = $db->get_mutant_name($mutant_id);
	    my $mutant_accession = get_canonical_accession(GR_PREFIX, $mutant_id);
            if($mutant_name eq 'NA'){
	      print td({-class=>'databody', -align=>'left'}, $i+1, '.', a({-target=>"mutant",-href=>EXE_NAME ."?id=$mutant_accession"}, $mutant_accession));
	    }else {
	      print td({-class=>'databody', -align=>'left'}, $i+1, '.', a({-target=>"mutant",-href=>EXE_NAME ."?id=$mutant_accession"}, $mutant_name));
	    }
            if($i==$total-1){  # for filling the empty space
                my $remain=3-$i%3;
                print td({-class=>'databody', -align=>'left',-colspan=>$remain},' ') if($remain !=1);
            }
            print end_TR if($i==$total-1 || ($i+1)%3==0);
         }
     
    }
############################################

    print TR(th({-align=>'left', -class=>'datatitle', -width=>'20%'}, 'Environmental Factors'), td({-colspan=>4, -class=>'databody'}, $study_environment)) if defined $study_environment;
    print end_table;

    if( $reference_ids_ref && scalar(@$reference_ids_ref) >0){
      ### 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});
      
      my $reference_count=0;
      foreach my $reference_id_ref (@$reference_ids_ref){
        my ($reference_id) = @$reference_id_ref;
	if($reference_count % 2 == 0) {
	  print start_TR({-class=>'databody', -align=>'center'});
	} else {
	  print start_TR({-align=>'center'}); 
	}
      
	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 = $reference_count + 1;

	print <<ITEM;
          <td align="LEFT">
            <dl>
              <dt>
                <table cellspacing="0" cellpadding="0">
                  <tr>
                    <td align="CENTER" valign="CENTER">
                      <img src="/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="/db/literature/pub_search?ref_id=$reference_id" target="reference">$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

      $reference_count += 1;
      }
      # tmp additioni
      print end_table;
    }
  }
  else{
    print h1("Sorry! Cannot find any information about <i>$input</i>");
  }

  print $page->end_body;
}
else{
  #default for no data available
  print $cgi->start_html(-title=>"Cannot find any information about $input", 
		         -style=>{'src'=>'/stylesheets/gramene.css'});
  #show Gramene::Page header
  print header();
  print $page->start_body;
  print_mutant_search_area();  
  print h1("Sorry! Cannot find any information about <i>$input</i>"); 
  print $page->end_body;
}

#####################################################################
# utility functions
#####################################################################
sub get_canonical_accession{
  my ($prefix, $id) = @_;
  my $canonical_accession = $prefix;
  my $length = MAX_LENGTH_OF_ACCESSION - length($id);
  for my $x (1 .. $length){
    $canonical_accession .= "0";
  }
  $canonical_accession .= $id;
  return $canonical_accession;
}

sub extract_ID{
  my $id = shift;
  my $is_study = 0;
  my $tmp = STUDY_PREFIX;
  
  if($id =~ /$tmp/) {
    $id =~ s/$tmp//;
    $id =~s/^0+//;
    $is_study = 1;
  } 
  undef $id unless(is_digit($id));
  
  return ($id, $is_study);
}

sub is_digit{
  my $query = shift;
  $query =~ s/^\s+//;
  $query =~ s/\s+$//;
  if ($query =~ /^\d+$/ ){
    return 1;
  }else{ 
    return 0;
  }
}

sub remove_spaces_on_both_sides{
  my $query = shift;
  $query =~ s/^\s+//;
  $query =~ s/\s+$//;
  return $query;
}

#################
sub print_mutant_search_area {
    my $self = url(-relative=>1);
    print start_form(-method=>'GET', -action=>"search_core");

  print <<SEARCH_AREA;
&nbsp;<img src="/images/icons/grain_icon.jpg" alt="grain_icon" height="16" width="16">
<a href="/rice_mutant/index.html" class="gopage">Gene Home</a> |
<a href="/rice_mutant/gene_search.html" class="gopage">Search</a> |
<a href="/rice_mutant/gene_submit.html" class="gopage">Submit</a> |
<a href="/rice_mutant/gene_help.html" class="gopage">Help Documents</a> |
<a href="/tutorials/mutant.html" class="gopage">Tutorial</a> |
<a href="/documentation/faq/mut_faq.html" class="gopage">FAQ</a>
<p></p>
<table align="center" cellspacing="0" cellpadding="3" border="0" width="98%" align=center>
 <tr> <th align=center class=searchtitle>Mutant Search</th></tr>
  <tr align=center class=searchbody>
    <td align=center>&nbsp;&nbsp;&nbsp;&nbsp;<input type=text value="" framewidth=4 name=query size=40 maxlength=256>&nbsp;&nbsp;&nbsp;&nbsp;<input name=btn type=submit value="Search">&nbsp;&nbsp;<input name=Clear type=reset value="Clear">
      <br><span class="alert">Search by Gene Symbol, Gene Name, Gramene Accesssion&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span>[e.g. <a href="/db/mutant/search_mutant?id=GR:0060198">dwarf-15</a> or <a href="/db/mutant/search_mutant?id=GR:0060198">GR:0060198</a>]&nbsp;&nbsp;<a href="/rice_mutant/Mutant_Help1.html">HELP</a> 
    </td>
  </tr>
</table>
SEARCH_AREA

  print end_form();
  print "<hr>";
}
