#####################################################################
#!/usr/bin/perl -w
# Mode: perl
# Programmer: Kuan Chang
# Date: 10/17/2001
#####################################################################

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

use DBI;
use CGI qw(:standard *table *TR *th *td *ul *ol);
use ODB;
use GL qw(:DEFAULT);
# use Apache;
use GramenePage;

#####################################################################
# constants
my $GO_PREFIX = "GO:";
my $TO_PREFIX = "TO:";
my $EXE_HOME ="/perl/ontology/";
my $EXE_NAME ="goterm";

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

my $input  = param('id');
my ($accession, $is_TO) = extract_accessionID($input);
my $id   = $input ?  $db->get_termID($accession, $is_TO) : undef;
my $name;
my $definition;
my $synonym;

if(defined $id ){
  $name       =  $db->get_name($id);
  $definition =  $db->get_definition($id);
  $synonym =  $db->get_synonym($id);
}

my $cgi = new CGI;
print $cgi->header;

if(defined $id){

my $go_accession =  $db->get_accession($id);

if($is_TO) {
  print $cgi->start_html(-title=>"Summary for TO Term: $name ($go_accession)",
			 -style=>{'src'=>'/stylesheets/gramene.css'});
}
else{
  print $cgi->start_html(-title=>"Summary for GO Term: $name ($go_accession)",
			 -style=>{'src'=>'/stylesheets/gramene.css'});  
}

print header();
print $page->start_body;

if($is_TO) {
  # print_top("Summary for TO Term: $name ($go_accession)");
  print_search_area();
  print h1("Summary for TO Term: <i>$name</i> ($go_accession)");
}
else {
  # print_top("Summary for GO Term: $name ($go_accession)"); 
  print_search_area();
  print h1("Summary for GO Term: <i>$name</i> ($go_accession)"); 
}
# print_search_area();
# print h1("Summary for Term <i>$name</i> ($go_accession)");
print start_table({-width=>'98%', -align=>'center', -cellpadding=>4, -cellspacing=>1});
print TR(th({-align=>'left', -class=>'datatitle', -width=>'12%'}, 'Term Name'), td({-class=>'databody'}, $name));
if(defined $synonym)
{
  print  TR(th({-align=>'left', -class=>'datatitle'}, 'Synonym'), td({-class=>'databody'}, $synonym||'No synonym available'));
}
if(defined $definition) 
{ 
  print  TR(th({-align=>'left', -class=>'datatitle'}, 'Definition'), td({-class=>'databody'},$definition||'No definition available'));
}
print end_table;

print_tree($id);
# print_immediate_family($id);
if(not $is_TO) {
print p("More information about this term can be found at",
        a({-target=>'_blank',-href=>"http://golgi.ebi.ac.uk/ego/QuickGO?mode=display&entry=$go_accession"},"the Interpro GO browser."));
}
}
else{
  print_top("Cannot find any information about $input");
  print_search_area();	
  print h1("Sorry! Cannot find any information about <i>$input</i>");
}
# print_bottom();
print $page->end_body;

sub print_tree {
  my ($id) = shift;
  my $self = url(-relative=>1);
  my $name  =  $db->get_name($id);	
  my $color_name = '<font color="red">'.$name.'</font>';	

#  print start_table({-width=>'100%',-cellpadding=>3, -cellspacing=>0});
#  print TR({-class=>'searchtitle'},th('Derivation(s)'));
#  print start_TR({-class=>'databody'}), start_td;
#=======
  print start_table({-width=>'98%',-align=>'center',-cellpadding=>3, -cellspacing=>0});
  print TR({-class=>'datatitle', -align=>'left'},th('Derivation'));
  print start_TR({-class=>'databody'}), start_td;

  my @paths = get_paths($id);
  my %seen_it;
  my $previous = 0;
  for my $path (@paths) {
    my $skip;
    for my $component (@$path) {
      print start_ul();
      if($seen_it{$component} && !$skip){
	$previous = $component;
      }
      next if $seen_it{$component}++ && !$skip;
      $skip++;
      print li($component eq $id ? ($db->get_relationship_symbol($previous, $component), b($color_name. " (".$db->get_accession($component).")" )) 
	       : ($db->get_relationship_symbol($previous, $component), object_link($component,b($db->get_name($component) ." (".$db->get_accession($component).")")))),"\n";	       
      #         : ObjectLink($component,b(GetName($component) ." (".GetGOAccession($component).")"))),"\n";
       $previous = $component;
    }
    if (my @children = $db->get_children($id)) {
      # print ul(li([map { a({-href=>"$self?id=$id"},$_->GetName . " ($_)") } @children]));
      print ul(li([map { $db->get_relationship_symbol($id, $_).a({-href=>"$self?id=".$db->get_accession($_)}, $db->get_name($_) . " (".$db->get_accession($_).")") } @children]));
    }
    print scalar(end_ul()."\n") x @$path;
  }
  print end_td,end_TR,end_table;
}

sub print_search_area {
  my $self = url(-relative=>1);
  print "<p align='center'><font size=-2>Type in ID or keyword to search for.</font>\n"; 
 # print table({-width=>'100%'},
 # TR({-class=>'searchtitle'},th("Search Gramene Ontology Database")));
  print start_form(-method=>'GET', -action=>"search");
  print table({-width=>'98%', -align=>'center'}, 
          TR({-class=>'searchtitle'},th("Search Gramene Ontology Database")),
	  TR({-align=>'center', -class=>'searchbody'}, td(textfield(-framewidth=>4, -name=>'query', -size=>55, -maxlength=>256))), 
	      TR({-align=>'center', -class=>'searchbody'}, td(submit(-name=>'btn', -value=>'Gramene Search'),reset(-name=>'Clear'))) );
  
#<td align=center><input type=text value="" framewidth=4 name=query size=55 maxlength=256><br><input name=btn type=submit value="GO Search"><input name=btn type=submit value="TO Search"></td
  print end_form();
  print "<br>", "<hr>";
}

sub print_immediate_family {
  my $id = shift;
  my $self = url(-relative=>1);
  my @parents = $db->get_parents($id);
  my @children = $db->get_children($id);

  print start_table({-width=>'100%',-cellpadding=>0,-cellspacing=>0});
  print TR({-align=>"center", -class=>'searchtitle'}, 
	   th('Parent Term(s)'." (".($#parents+1).")"),
	   th('Child Term(s)'." (".($#children+1).")"));

  print start_TR({-class=>'searchbody'}), start_td;
  print ul(li([map { a({-href=>"$self?id=".$db->get_accession($_)}, $db->get_name($_) . " (".$db->get_accession($_).")") } @parents]));
  print end_td, start_td;
  print ul(li([map { a({-href=>"$self?id=".$db->get_accession($_)}, $db->get_name($_) . " (".$db->get_accession($_).")") } @children]));
  print end_td,end_TR,end_table;
}

sub get_paths {
  my $id    = shift;
  my @result;
  my @parents = $db->get_parents($id);
  return [$id] unless @parents;
  for my $parent (@parents) {
    my @paths = get_paths($parent);
    push @result,[@$_,$id] foreach @paths;
  }
  @result;
}

sub object_link {
  my($term_id,$title) = @_;
  my $accession = $db->get_accession($term_id);
  my $href = "$EXE_HOME$EXE_NAME?id=$accession";
  return a({-href=>$href},$title);
}

# utility functions
sub extract_accessionID{
  my $id = shift;
  my $is_TO = 0;
  if($id =~ /$TO_PREFIX/) {
    $id =~ s/$TO_PREFIX//;
    $is_TO = 1;
  }
  else{
    $id =~ s/$GO_PREFIX//;
  }
  return ($id, $is_TO);
}
