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

use strict;
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:';
use constant PO_PREFIX => 'GRO:';
# GR_PREFIX is for mutant
use constant GR_PREFIX => 'GR:';
use constant STUDY_PREFIX => 'GR:ST:';
use constant ALLELE_PREFIX => 'GR:AL:';
use constant GERMPLASM_PREFIX => 'GR:GP:';
use constant EXE_NAME => 'search_mutant';
use constant ONTOLOGY_HOME => '/db/ontology/';
use constant GERMPLASM_EXE_NAME => 'search_germplasm';
use constant ONTOLOGY_EXE_NAME => 'search_term';
use constant STUDY_EXE_NAME => 'search_study';
use constant ALLELE_EXE_NAME => 'search_allele'; 
use constant SEARCH_PROTEIN_EXE_NAME => 'protein_search';
use constant MUTANT_IMAGE_HOME => '/images/mutant/';
use constant MAX_LENGTH_OF_ACCESSION => 7;



#####################################################################
# 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_allele);
undef $id;
($id, $is_allele) = extract_ID(ALLELE_PREFIX, $input);

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

if(defined $id && $is_allele){
  my $allele = $db->get_allele($id);
  

      
    my($allele_id, $allele_designation, $allele_description, $allele_interaction_description) = split(/\t/,$allele) if $allele;
    my @allele_studies = $db->get_allele_studies($id) if $allele ; 
    my @allele_to_mutants = $db->get_allele_to_mutants($id) if $allele ;
    my @allele_germplasms = $db->get_germplasms('allele', $id);
    my $phenotypesRef = $db->get_object_phenotypes( 'allele', $id, );
    my %phenotypes = %$phenotypesRef;
   

     #check if parameters are empty, set them undefined
    undef $allele_designation unless $allele_designation;
   undef $allele_description unless $allele_description;
    undef $allele_interaction_description unless $allele_interaction_description;
   undef @allele_studies unless @allele_studies;
    undef @allele_to_mutants unless @allele_to_mutants;
    undef @allele_germplasms unless @allele_germplasms;
  undef %phenotypes unless (%phenotypes && scalar( keys %phenotypes)>0 );
  
#######################################################################
  if(defined $allele) {
    print $page->start_html(-title=>"Summary for Rice Allele: $allele_designation ($input)  "); 
  }
  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 $allele) {


    print h1("Summary for Rice Allele: <i>$allele_designation</i> ($input) ");
    print start_table({-width=>'98%', -align=>'center', -cellpadding=>4, -cellspacing=>1});
   # print TR(th({-align=>'center', -class=>'datatitle', -colspan=>'6'},"General information" ));

    $allele_designation =~ s/^(\D+)/<i>$1\<\/i>/;	
    print TR(th({-align=>'left', -class=>'datatitle', -width=>'20%'}, 'Allele symbol'), td({-class=>'databody'}, $allele_designation));
   
   # if($allele_name && $allele_name ne 'NA'){
 #print TR(th({-align=>'left', -class=>'datatitle', -width=>'20%'}, 'Allele Name'),td({-colspan=>'4',-class=>'databody'}, $allele_name)); 
  #  }

   
    # if($allele_synonym){
 #print TR(th({-align=>'left', -class=>'datatitle', -width=>'20%'}, 'Allele Synonym'),td({-colspan=>'4',-class=>'databody'}, $allele_synonym)); 
  #  }

    print TR(th({-align=>'left', -class=>'datatitle', -width=>'20%'}, 'Allele Description'), td({-class=>'databody'}, $allele_description));	

   if(defined $allele_interaction_description){	
     print TR(th({-align=>'left', -class=>'datatitle', -width=>'20%'}, 'Description of Allelic Interaction'), td({-class=>'databody'}, $allele_interaction_description));
   }
 


    
    if(@allele_studies){
      print start_TR;
     
      print th({-align=>'left', -class=>'datatitle', -width=>'20%'}, 'Study');
      my $study_count = 1;
      foreach my $allele_study(@allele_studies){
	my ($study_id, $study_name, $year, $season, $geographical_location_id, $study_type, $environmental_factors) = split("\t", $allele_study); 
	my $study_accession = get_canonical_accession(STUDY_PREFIX, $study_id);
        if($study_name ne 'NA'){           
	   print td({-class=>'databody', -align=>'left'}, $study_count, '.', a({-target=>'study',-href=>STUDY_EXE_NAME ."?id=$study_accession"}, $study_name));
        }else{
            print td({-class=>'databody', -align=>'left'},  a({-target=>'study',-href=>STUDY_EXE_NAME ."?id=$study_accession"},  $allele_designation."-".$study_count));
        }
       
	$study_count += 1;
       }
      print end_TR;
    }

   if(@allele_germplasms){
     my $count_germplasm = @allele_germplasms;
     print start_TR;
     print th({-align=>'left', -class=>'datatitle', -width=>'20%' }, "Germplasm");
     my @linked_germplasms;
     for( my $i = 0; $i <$count_germplasm; $i++ ) {
         my @allele_germplasm_columns =  split("\t", $allele_germplasms[$i]);
	 my $germplasm_accession = get_canonical_accession(GERMPLASM_PREFIX, $allele_germplasm_columns[0]);
	 my $germplasm_link = '<a target="germplasm" href="'.GERMPLASM_EXE_NAME ."?id=$germplasm_accession".'">'.$allele_germplasm_columns[1].'</a>';
	 push @linked_germplasms, $germplasm_link;
     }

     print td({-class=>'databody',-align=>'left'},join(", ", @linked_germplasms)); 
     print end_TR;
     
 }
 
     if(@allele_to_mutants){
      print start_TR;
      print th({-align=>'left', -class=>'datatitle', -width=>'20%'}, 'Gene');
      my $mutant_count = 1;
      foreach my $mutant_id(@allele_to_mutants){
      
	my $mutant_name = $db->get_mutant_name($mutant_id);
	my $mutant_accession = get_canonical_accession(GR_PREFIX, $mutant_id);
      
	print td({-class=>'databody', -align=>'left'}, $mutant_count, '.', a({-target=>'mutant',-href=>EXE_NAME ."?id=$mutant_accession"}, $mutant_name));
        
	$mutant_count += 1;
       }
      print end_TR;
    }
    print end_table;



  if( %phenotypes ) {

    print "<br>";

    print start_table({-border=>1, -width=>'98%', -align=>'center', -cellpadding=>4, -cellspacing=>1});
    print TR(th({-align=>'left', -class=>'datatitle', -width=>'20%', -colspan=>'2'},
    q[ <a name="feature"></a>Associated Feature
	&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
	( Evidence Code: 
	<a href="/plant_ontology/evidence_codes.html#TAS" target="evn">TAS</a>
	<a href="/plant_ontology/evidence_codes.html#IAGP" target="evn">IAGP</a>
	)
    ]));


    foreach my $term_type (keys %phenotypes){
	my $term_accs = $phenotypes{$term_type};
	my %linked_terms;
	foreach my $term_acc (@$term_accs){
	    my $term_name = $db->get_term_name($term_acc);
	    $term_name ||= $term_acc;
	    my $term_link =  '<a target="ontology" href="'.ONTOLOGY_HOME.''.ONTOLOGY_EXE_NAME."?id=$term_acc".'">'.$term_name.'</a>';
	    my $links = $linked_terms{$term_name};
	    if($links){
		$linked_terms{$term_name} = $links.", $term_link";
	    }else{
		$linked_terms{$term_name} = $term_link;
	    }
	}

	my $sorted_linked_terms = ''; # sort terms for displaying
	foreach my $term_name ( sort keys %linked_terms){
	    my $links = $linked_terms{$term_name};
	    $sorted_linked_terms = 
		$sorted_linked_terms ?
		"$sorted_linked_terms, $links" 
		: "$links";
	}


	print start_TR;
	print th({-align=>'left', -class=>'datatitle', -width=>'20%'}, "$term_type");
	print td({-class=>'databody', -align=>'left'}, $sorted_linked_terms);
	print end_TR;
    }


    print end_table;
  

  
 }



 } #for $allele exist
 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 ($prefix, $id) = @_;
  my $is_target = 0;
  
  if($id =~ /$prefix/) {
    $id =~ s/$prefix//;
    $is_target = 1;
  } 
  undef $id unless(is_digit($id));
  
  return ($id, $is_target);
}

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>Gene 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>";
}
