package GoCurationPage;

##########################################################
#                                                        #
# dictyBase Extension of GoCurationPage                  #
#                                                        #
##########################################################

use GoCurationPage_base;
use DictyBaseConfig;
use dicty::GO::GOGeneAssociation;
BEGIN { %GoCurationPage:: = %GoCurationPage_base:: }

#######################################################################
sub new {      ############ constructor ###############################
#######################################################################

        my ($self, %args) = @_;

        $self = {};
        bless $self;

        $self->{'_database'} = $args{'database'};
        $self->{'_help'}     = defined($args{'help'}) ?
                               $args{'help'} : "usingGO.html";
        $self->{'_title'}    = defined($args{'title'}) ?
                               $args{'title'} : "GO Curation Page";
        $self->{'_user'}     = defined($args{'user'}) ? $args{'user'} : "";
        $self->{'_feat'}     = defined($args{'feat'}) ? $args{'feat'} : "";
        $self->{'_type'}     = defined($args{'type'}) ? $args{'type'} : "";
        $self->{'schema'} = undef; ### Added by sohel to add the schema element ###
        $dbh = &ConnectToDatabase($self->database);
            return $self;
}



########################################################################
sub displayRowsFromDB {
########################################################################
    my ($self) = shift;
    my ($title, $subtitle, $No, $tabNm);
    if ($self->{'_featNm'} && $self->{'_locusNm'}) {
        $title = $self->title." for ".$self->{'_featNm'}."/".$self->{'_locusNm'};
        $subtitle = $self->{'_featNm'}."/".$self->{'_locusNm'};
    }
    elsif ($self->{'_featNm'}) {
        $title = $self->title." for ".$self->{'_featNm'};
        $subtitle = $self->{'_featNm'};
    }
    elsif ($self->{'_locusNm'}) {
        $title = $self->title." for ".$self->{'_locusNm'};
        $subtitle = $self->{'_locusNm'};
    }
    &printStartPage($self->database, $title, $self->help);
    if (!$self->{'_locusNm'}) {
        $self->printSubtitle($subtitle, $self->{'_featNm'},
                             "(feature_no=$self->{'_featNo'})");
        $No = $self->{'_featNo'};
        $tabNm = "GO_FEAT_GOEV";
    }
    else {
        $self->printSubtitle($subtitle, $self->{'_locusNm'},
                             "(locus_no=$self->{'_locusNo'})");
        $No = $self->{'_locusNo'};
        $tabNm = "GO_LOCUS_GOEV";
    }
    print startform;
    print "<table border=1 cellpadding=1 cellspacing=1>";
    my $goidArrayRef;
    if (!$self->{'_locusNm'}) {
        my $featObj = Feature->new(dbh=>$dbh,
                                   feature_no=>$self->{'_featNo'});
        $goidArrayRef = $featObj->goidArrayRef;
    }
    else {
        my $locusObj = Locus->new(dbh=>$dbh,
                                  locus_no=>$self->{'_locusNo'});
        $goidArrayRef = $locusObj->goidArrayRef;
    }
    my $i = 0;
    my %FOUNDannotation;
    my $count;
    foreach my $rowRef (@$goidArrayRef) {
        my ($goid) = @$rowRef;
        $count++;
        if ($count == 1) {
            $self->printHeaderRow4existingInfo;
        }
        my $go = Go->new(dbh=>$dbh,
                         goid=>$goid);

        my $goAspect = $go->go_aspect;
        my $goTerm = $go->go_term;
        my $schema = $go->schema;
        $self->{'schema'} = $go->schema;
        my $paperEtcRef;
        #### assume each paper has a unique IS_NOT value
        #### following query will return paper::is_not array ref
        if ($self->{'_locusNm'}) {
            $paperEtcRef = Go->GetReferenceInfoNew(
                                         dbh=>$dbh,
                                         goid=>$goid,
                                         type=>'LOCUS',
                                         No=>$self->{'_locusNo'});
        }
        else {
            $paperEtcRef = Go->GetReferenceInfoNew(
                                         dbh=>$dbh,
                                         goid=>$goid,
                                         type=>'FEATURE',
                                         No=>$self->{'_featNo'});
        }

        foreach my $paperRowRef (@$paperEtcRef) {
                my ($refNo, $paper, $goevNo, $goevCode, $isNot, $dateCreated,
                    $externalIdNo, $externalId, $source) = @$paperRowRef;
                $i++;
                $paper = $paper." (refNo=$refNo)";
                my $shared = "no";
                foreach my $rowRef (@{$go->getLocusArrayRef}) {
                    my ($locus_no, $locus_name) = @$rowRef;
                    if ($locus_no != $self->{'_locusNo'}) {
                        $shared = "yes";
                        last;
                    }
                }
                if ($shared == "no") {
                    foreach my $rowRef (@{$go->getFeatureArrayRef}) {
                        my ($feature_no, $feature_name) = @$rowRef;
                        if ($feature_no != $self->{'_featNo'}) {
                            $shared = "yes";
                            last;
                        }
                    }
                }

############# The following code was added by Sohel merchant to take care of retriving the external id from the go_locus_goev and go_annotation_with_from table
my $schema = $self->{'schema'};
my $with_from_sth = $dbh->prepare("select external_db, external_id, gl.with_from from $schema.go_locus_goev gl, $schema.go_annotation_with_from gw where goid = ? and locus_no = ? and go_evidence_no = ? and is_not = ? and gl.with_from = gw.id");
$with_from_sth->execute($goid,$No,$goevNo,$isNot);
($source,$externalId,$externalIdNo) = $with_from_sth->fetchrow();
$with_from_sth->finish();
################################################################################################################


                my $deleteAnnot = "";
                $goAspect =~ s/^P$/Process/;
                $goAspect =~ s/^F$/Function/;
                $goAspect =~ s/^C$/Component/;
                print hidden("ontologyDB$i", "$goAspect"),
                      hidden("goidDB$i", "$goid"),
                      hidden("goTermDB$i", "$goTerm"),
                      hidden("isNotDB$i", "$isNot"),
                      hidden("referenceDB$i", "$paper"),
                      hidden("refNoDB$i", "$refNo"),
                      hidden("goEvNoDB$i", "$goevNo"),
                      hidden("goEvCodeDB$i", "$goevCode"),
                      hidden("externalIdNoDB$i", "$externalIdNo"),
                      hidden("externalIdDB$i", "$externalId"),
                      hidden("sourceDB$i", "$source"),
                      hidden("sharedDB$i", "$shared");
                my $displayGoTerm = $goTerm;
                if ($isNot =~ /Y/i) {
                    $displayGoTerm = b(font({color=>'red'},"NOT ")).$goTerm;
                }
                $self->printOneRow4existingInfo($i, $goAspect, $goid,
                                                $displayGoTerm,
                                                $paper, $goevCode,
                                                $externalId, $source,
                                                $deleteAnnot, $shared);
        }
    }

    print "</table>";
    print  "<br><center>",submit('commit','Submit'),"  ",reset,"</center>";
    print "<p><table>";
    $self->printNewEntryTitle;
    $self->printMoreRows(1);
    print "</table>";
    $self->printEndForm($self->{'_featNm'}, $self->{'_featNo'},
                        $self->{'_locusNm'}, $self->{'_locusNo'});
    &printEndPage;
}



########################################################################
sub commitInfo {
########################################################################
    my ($self) = shift;
    my ($title, $type, $locusORfeatNo);

    if (param('locusNm') && param('featNm')) {
        $title = $self->title." for ".param('featNm')."/".param('locusNm');
        $locusORfeatNo = param('locusNo');
        $type = "locus";
    }
    elsif (param('featNm')) {
        $title = $self->title." for ".param('featNm');
        $locusORfeatNo = param('featNo');
        $type = "feature";
    }
    elsif (param('locusNm')){
        $title = $self->title." for ".param('locusNm');
        $locusORfeatNo = param('locusNo');
        $type = "locus";
    }
    &printStartPage($self->database, $title, $self->help);
    ######################

    my %goEvidenceNo;
    Go->GetGoEvidenceInfo(dbh=>$dbh,
                          goEvidenceNoRef=>\%goEvidenceNo);
    for (my $i = 1; $i <= 100; $i++) {
        my $goid = param("goidDB$i");
        if (!$goid) { last;}
        if (param("deleteAnnot$i") =~ /on/i) {
            my $refNo = param("refNoDB$i");
            my $externalIdNo = param("externalIdNoDB$i");
            my $goevNo = param("goEvNoDB$i");
            #print "Deleting annotation<br>";
            Go->DeleteAnnotationNew(dbh=>$dbh,
                                    reference_no=>$refNo,
                                    goid=>$goid,
                                    No=>$locusORfeatNo,
                                    type=>$type,
                                    evidence_code_no=>$goevNo,
                                    external_id_no=>$externalIdNo);
            print font({-color=>'red'},b("The annotation for goid='$goid', ${type}_no='$locusORfeatNo', reference_no='$refNo', evidence_code_no='$goevNo', and external_id_no='$externalIdNo' has been deleted from database.")).p;
        }
    }

    ###### new entries:

    for (my $i = 1; $i <= 100; $i++) {
        my $update = 0;
        my $goid = param("goid$i");
        $goid =~ s/^0+//;
        &DeleteUnwantedChar(\$goid);
        if ( !$goid) { last; }

        my $col_with =  param("col_with$i");
        my $cont_to =   param("cont_to$i");

        my $refNo = param("refNo$i");
        $refNo =~ s/^0+//;
        &DeleteUnwantedChar(\$refNo);
        my $pubmed = param("pubmed$i");
        $pubmed =~ s/^0+//;
        &DeleteUnwantedChar(\$pubmed);
        if (!$refNo && !$pubmed) {
            next;
        }
        if (!$refNo && $pubmed) {
            my $refObject = Pubmed->new(dbh=>$dbh,
                                             pubmed=>$pubmed);
            $refNo = $refObject->referenceNo;
            if (!$refNo) {
                print "The pubmed=$pubmed is not found in database or can't create medline paper for it from NCBI.", p;
                next;
            }
        }
        else {
            my $refObj = Reference->new(dbh=>$dbh,
                                        reference_no=>$refNo);
            if (!$refObj) {
                print "The reference_no=$refNo is not found in database.", p;
                exit;
            }

        }
        my $isNot = param("isNot$i");
        if ($isNot) { $isNot = 'Y'; }
        else { $isNot = 'N'; }

        my $col_with = param("col_with$i");
        if ($col_with) { $col_with = 'Y'; }
        else { $col_with = 'N'; }

        my $cont_to = param("cont_to$i");
        if ($cont_to) { $cont_to = 'Y'; }
        else { $cont_to = 'N'; }



        my $go = Go->new(dbh=>$dbh,
                         goid=>$goid);

        if (!$go) {
            print font({-color=>'red'},b("The goid you entered ($goid) is not found in GO table. This entry can not be committed into database.")).p;
            next;
        }
        $self->{'schema'} = $go->schema();
        my $goAspect = param("ontology$i");
        if ($goAspect =~ /ontology/i || !$goAspect) {
            print "<p>You have to select ontology before press the Submit button. Please go back, make all necessary selection and try again.<p>";
            exit;
        }
        my @goevCode = param("goEvCode$i");
        if (!@goevCode) {
            print "<p>You have to select the go_evidence_code before press the Submit Button. Please go back, make any necessary selection and try again.<p>";
            exit;
        }
        my $goevCodeList = join(":", @goevCode);
        if ($goevCodeList =~ /IC/i && !param("ICgoid$i")) {
            print p("You have to enter 'IC from GOid' if you select 'IC' evidence code. Please go back, make any necessary change and try again."), p;
            exit;
        }
        my @goevCode4withFrom = param("goEvCode4withFrom$i");
        my %foundGoEv;
        foreach my $goevCode (@goevCode) {
            $foundGoEv{$goevCode}++;
        }
        my %isWithFrom;
        foreach my $goevCode (@goevCode4withFrom) {
            if (!$foundGoEv{$goevCode}) {
                push(@goevCode, $goevCode);
            }
            $isWithFrom{$goevCode}++;
        }
        my $source = param("DB$i");
        my $ID = param("ID$i");
        &DeleteUnwantedChar(\$ID);
        my $ICgoid = param("ICgoid$i");
        &DeleteUnwantedChar(\$ICgoid);
        #$ICgoid =~ s/^GO:0*//;
        #$ICgoid =~ s/^0+//;
        my $goAspectDB = $go->go_aspect;
        my $goTermDB = $go->go_term;
        if ($goAspect ne $goAspectDB) {
            $goAspectDB =~ s/C/Cellular Component/;
            $goAspectDB =~ s/F/Function/;
            $goAspectDB =~ s/P/Process/;
            $goAspect =~ s/C/Cellular Component/;
            $goAspect =~ s/F/Function/;
            $goAspect =~ s/P/Process/;
            print "The GOID $goid is associated with the go_term '$goTermDB' in the $goAspectDB ontology, not the $goAspect ontology. Please go back and make a correction.<p>";
            exit;
        }

        my $locuslist = param("locuslist$i");
        my $featlist = param("featlist$i");
        &DeleteUnwantedChar(\$locuslist);
        &DeleteUnwantedChar(\$featlist);
        my @loci = split(/\|/, $locuslist);
        my @feats = split(/\|/, $featlist);
        my $featNum = 0;
        foreach my $feat (1, @loci, @feats) {
            ### 1 -- for current locus or feature name
            $featNum++;
            my $THISlocusORfeatNo = $locusORfeatNo;
            my $THIStype = $type;
            if ($featNum > 1) {
                if ($featNum <= @loci + 1) { ### it is locus in the locuslist
                    my $locus = Locus->new(dbh=>$dbh,
                                           locus_name=>$feat);
                    if (!$locus) {
                        print "The locus ($feat) is not in locus table in database.", p;
                        next;
                    }
                    $THISlocusORfeatNo = $locus->locus_no;
                    $THIStype = "locus";
                }
                else {  ### it is feature in the featlist
                    my $feature = Feature->new(dbh=>$dbh,
                                               feature_name=>$feat);
                    if (!$feature) {
                        print "The feature ($feat) is not in feature table in database.", p;
                        next;
                    }
                    $THISlocusORfeatNo = $feature->feature_no;
                    $THIStype = "feature"
                }
            }

            foreach my $goevCode (@goevCode) {

                my $goevNo = $goEvidenceNo{$goevCode};
                my ($tabNm, $prikeyCol);
                if ($THIStype =~ /locus/i) {
                    my $goLocusGoev = Go_locus_goev->new(
                                              dbh=>$dbh,
                                              goid=>$goid,
                                              locus_no=>$THISlocusORfeatNo,
                                              go_evidence_no=>$goevNo,
                                              is_not=>$isNot);

                    if (!$goLocusGoev) { ## is not in db. Insert it
                        eval {
#                              my $gga = dicty::GO::GOGeneAssociation->new(-GOID => $goid, -LOCUS_NO => $THISlocusORfeatNo, -EVIDENCE_CODE_NO => $goevNo, -IS_NOT => $isNot, -COLOCALIZES_WITH => 'GO:16892', -CONTRIBUTES_TO => 'DNA-dependent RNA polymerase activity');
# # #                          print "GOID --> $goid <br>";
#                              $gga->insert();
                            Go_locus_goev->Insert(dbh=>$dbh,
                                             binds=>{goid=>$goid,
                                                     locus_no=>$THISlocusORfeatNo,
                                                     go_evidence_no=>$goevNo,
                                                     is_not=>$isNot,
                                                     is_colocalizes_with => $col_with,
                                                     is_contributes_to => $cont_to
                                                     });
                        };
                        if ($@) {
                            print "An error occurred when inserting Go_Locus_Goev entry into database.$@", br;
                            $dbh->rollback;
                        }
                        else {
                            $dbh->commit;
                            print "The Go_Locus_Goev entry for goid='$goid', locus_no='$THISlocusORfeatNo' and goevNo='$goevNo' has been inserted into database.", p;
                        }
                    }
                    else {
                        print "The Go_Locus_Goev entry for goid='$goid', locus_no='$THISlocusORfeatNo' and goevNo='$goevNo' is already in database.", p;
                    }
                    $tabNm = "GO_LOCUS_GOEV";
                    $prikeyCol = "GOID::LOCUS_NO::GO_EVIDENCE_NO::IS_NOT";
                }
                else {
                    my $goFeatGoev = Go_feat_goev->new(
                                              dbh=>$dbh,
                                              goid=>$goid,
                                              feature_no=>$THISlocusORfeatNo,
                                              go_evidence_no=>$goevNo,
                                              is_not=>$isNot);

                    if (!$goFeatGoev) { ## is not in db. Insert it
                        eval {
                            Go_feat_goev->Insert(dbh=>$dbh,
                                              binds=>{goid=>$goid,
                                                      feature_no=>$THISlocusORfeatNo,
                                                      go_evidence_no=>$goevNo,
                                                      is_not=>$isNot});
                        };
                        if ($@) {
                            print "An error occurred when inserting Go_Feat_Goev entry into database.$@", br;
                            $dbh->rollback;
                        }
                        else {
                            $dbh->commit;
                            print "The Go_Feat_Goev entry for goid='$goid', feature_no='$THISlocusORfeatNo' and goevNo='$goevNo' has been inserted into database.", p;
                        }
                    }
                    else {
                        print "The Go_Feat_Goev entry for goid='$goid', feature_no='$THISlocusORfeatNo' and goevNo='$goevNo' is already in database.", p;
                    }
                    $tabNm = "GO_FEAT_GOEV";
                    $prikeyCol = "GOID::FEATURE_NO::GO_EVIDENCE_NO::IS_NOT";
                }
                my $prikey = $goid."::".$THISlocusORfeatNo."::".$goevNo."::".$isNot;

                my $reflinkObj = Reflink->new(dbh=>$dbh,
                                                  reference_no=>$refNo,
                                                  tab_name=>$tabNm,
                                                  primary_key=>$prikey,
                                                  primary_key_col=>$prikeyCol);

                if (!$reflinkObj) {

                    eval {
                        Reflink->Insert(dbh=>$dbh,
                                    literals=>{reflink_no=>'CGM_DDB.reflinkno_seq.nextval'},
                                    binds=>{reference_no=>$refNo,
                                            tab_name=>$tabNm,
                                            primary_key=>$prikey,
                                            primary_key_col=>$prikeyCol}
                                    );
                    };
                    if ($@) {
                        print "An error occurred when inserting reference_no='$refNo', tab_name='$tabNm', primary_key_col='$prikeyCol', and primary_key='$prikey' into reflink table. see following error msg.<br>$@", p;
                        $dbh->rollback;
                    }
                    else {
                        print "The reflink info for reference_no='$refNo', tab_name='$tabNm', primary_key_col='$prikeyCol', and primary_key='$prikey' has been inserted into database.", p;

                        $reflinkObj = Reflink->new(dbh=>$dbh,
                                                  reference_no=>$refNo,
                                                  tab_name=>$tabNm,
                                                  primary_key=>$prikey,
                                                  primary_key_col=>$prikeyCol);

                    }
                }
                else {

                    print "The reflink entry for reference_no='$refNo', tab_name='$tabNm', primary_key_col='$prikeyCol', and primary_key='$prikey' is already in database.",p;

                }

                if (!$reflinkObj) { next; }

                if (($isWithFrom{$goevCode} && $source && $ID) ||
                        ($goevCode eq "IC" && $ICgoid)) {

                        my $prikey = $reflinkObj->reflink_no;

                        my $tabNm = "REFLINK";

                        my $thisSource = $source;

                        my $thisID = $ID;

                        if ($goevCode eq "IC" && $ICgoid) {
                            $thisSource = 'GO';
                            $thisID = $ICgoid;
                        }

                        my @ID = split(/\|/, $thisID);

                        if($thisID)
                        {
#                        foreach my $thisID (@ID) {

                            &DeleteUnwantedChar(\$thisID);
                            eval {

                                ############ Added by Sohel Merchant to update the with_from coulumn of the go_locus_goev table. This has the possible problem that the corresponding blast information associated with it dosen't necesarily have to be correct #######
                                my $schema = $self->{'schema'};

                                my $insertflag = 1;
                                my $with_from_id;
                                my $exist_with_from_sth = $dbh->prepare("select id, external_id, external_db from $schema.go_annotation_with_from where blast_id is null");
                                $exist_with_from_sth->execute();
                                while(my @myarr = $exist_with_from_sth->fetchrow_array())
                                {
                                 $myarr[2] =~ s/ //g;
                                 $thisSource =~ s/ //g;
                                $myarr[1] =~ s/ //g;
                                $thisID =~ s/ //g;

                                if(($myarr[1] eq $thisID) && ($myarr[2] eq $thisSource))
                                {
                                           #print "$myarr[0] $myarr[1] $myarr[2] $myarr[3]<br>";
                                           $insertflag = 0;
                                           $with_from_id = $myarr[0];
                                           last;
                                }
                                }

                                if($insertflag == 1)
                                {
                                    my $insert_GO_with_sth = $dbh->prepare("insert into $schema.GO_ANNOTATION_WITH_FROM values ($schema.GO_WITH_FROM_SEQUENCE.NextVal,?,?,'',SYSDATE,'Curator')");
                                    $insert_GO_with_sth->execute($thisSource,$thisID);
                                    $insert_GO_with_sth->finish();
                                    $dbh->commit();
                                    ### The following needs to to executed again instead of using currval function on the go_annotation_wth_from table to make sure that their is no 2 people using the system concurrenlty and creating errors. ############
                                    my $exist_with_from_sth = $dbh->prepare("select id, external_id, external_db from $schema.go_annotation_with_from where blast_id is null");
                                    $exist_with_from_sth->execute();
                                    while(my @myarr = $exist_with_from_sth->fetchrow_array())
                                    {
                                            $myarr[2] =~ s/ //g;
                                            $thisSource =~ s/ //g;
                                            $myarr[1] =~ s/ //g;
                                            $thisID =~ s/ //g;

                                            if(($myarr[1] eq $thisID) && ($myarr[2] eq $thisSource))
                                            {
                                                 #print "$myarr[0] $myarr[1] $myarr[2] $myarr[3]<br>";
                                                 $with_from_id = $myarr[0];
                                                 last;
                                            }
                                    }
                                }

                                my $go_locus_goev_sth = $dbh->prepare("update $schema.go_locus_goev set with_from = ? where goid = ? and locus_no = ? and go_evidence_no = ? and is_not = ? ");
                                $go_locus_goev_sth->execute($with_from_id,$goid,$THISlocusORfeatNo,$goevNo,$isNot);
                                $go_locus_goev_sth->finish();
                                $dbh->commit();

                                ########################################################
                                # External_id->Insert(dbh=>$dbh,
#                                              literals=>{external_id_no=>'CGM_DDB.extidno_seq.nextval'},
#                                              binds=>{external_id=>$thisID,
#                                                 source=>$thisSource,
#                                                 tab_name=>$tabNm,
#                                                 primary_key=>$prikey});

                            };
                            if ($@) {
                                print "An error occurred when inserting external_id='$thisID', source='$thisSource', tab_name='$tabNm', and primary_key='$prikey' into external_id table. See following error msg. :$@:", p;
                                $dbh->rollback;
                            }
                            else {
                                print "The external_id entry for external_id='$thisID', source='$thisSource', tab_name='$tabNm', and primary_key='$prikey' has been inserted into database.",p;
                            }
                        }

                        $update++;
                }
            }
        }

    }

    ##################
    if (param('locusNm')) {
        print p, b("View locus ".a({ #-href=>$configUrl->dictyBaseCGIRoot."$dblink/locus.pl?locusName=".param('locusNm'),
                                    -href=>"/gene/".param('locusNm'),
                                    -target=>'infowin'}, param('locusNm')));
    }
    elsif (param('featNm')) {
        print p, b("View feature ".a({-href=>$configUrl->dictyBaseCGIRoot."$dblink/locus.pl?featureName=".param('featNm'),-target=>'infowin'}, param('featNm')));
    }
    print p, b("Return to ".a({-href=>$configUrl->dictyBaseCGIRoot."$dblink/curatorLogin?user=".$self->user}, "dictyBase Curator Central")), br;
    ##################

    ##################
    &printEndPage;
    ##################
}



########################################################################
sub goWithFromField {
########################################################################
    my ($self, $i, $defaultSource, $ID, $ICgoid, $goevRef4withFrom) = @_;

    my $DBcodeFile = $configPath->dataDir."dictyBase_GO_DB_code_mapping";
    #print $configPath->dataDir."\n";
    open(IN, "$DBcodeFile") ||
        die "Can't open '$DBcodeFile' for reading:$!\n";

    my @sourceValues;

    my %isDBcode = {};
    while(<IN>) {
        my ($dbCode, $goCode) = split(/\t/);
        $goCode =~ s/\s//g;
        $isDBcode{$dbCode} = $goCode;
        push(@sourceValues, $goCode);
        @sourceValues = sort @sourceValues;
    }
    close(IN);


  # ################### added by sohel merchant ############3
#     my $extdb_sth = $dbh->prepare("select unique external_db from go_annotation_with_from");
#     $extdb_sth->execute();
#     my @extdb;
#     while(my $db = $extdb_sth->fetchrow)
#     {
#            $db =~ s/ //;
#            push(@extdb,$db);
#     }
#     print $isDBcode{'SGD'}."<br>";
#     foreach my $source (@extdb) {
#         print Dumper(%isDBcode);
#         if ($isDBcode{$source}) {
#             push(@sourceValues, $source);
#             print "inside\n";
#             delete $isDBcode{$source};
#         }
#     }
    ######################################################################
    #my $arrayRef = External_id->GetUniqueSource(dbh=>$dbh);
    # foreach my $rowRef (@$arrayRef) {
#         my ($source) = @$rowRef;
#         if ($isDBcode{$source}) {
#             push(@sourceValues, $source);
#             print "inside\n";
#             delete $isDBcode{$source};
#         }
#     }

   #  foreach my $code (keys %isDBcode) {
#         print font({-color=>'red'}, "Warning: The code '$code' is not found in database."), br;
#     }

    return table(Tr(td(checkbox_group(-name=>"goEvCode4withFrom$i",
                                      -values=>['IGI', 'IPI', 'ISS', 'IEA'],
                                      -default=>\@$goevRef4withFrom).b(" with:"))
                 ).
                 Tr(td(b("DB:").
                       popup_menu(-name=>"DB$i",
                                  -values=>\@sourceValues,
                                  -default=>$defaultSource))
                 ).
                 Tr(td({-align=>'left'},
                       b("ID:").
                       textfield(-name=>"ID$i",
                                 -value=>"$ID",
                                 -size=>'12').br."separate multiples by |")
                 ).
                 Tr(td(a({-href=>'http://www.geneontology.org/doc/GO.xrf_abbs'}, "List of DB:ID's"))).
                 Tr(td(b(font({-size=>'+1'}, "---- OR ----")))).
                 Tr(td({-align=>'left'},
                       b("IC from GOid:").
                       textfield(-name=>"ICgoid$i",
                                 -value=>"$ICgoid",
                                 -size=>'12').br."separate multiples by |")
                 )
           );

}

########################################################################
sub headerRow {
########################################################################
    return Tr(td({-align=>'center'},
                        b(font({-size=>'-1'},
                               "Choose Ontology"))).
              td({-align=>'center'},
                        b(font({-size=>'-1'},
                               "Enter GO ID number"))).
              td({-align=>'center'},
                        b(font({-size=>'-1'},
                               "Qualifier"))).
              td({-align=>'center'},
                        font({-size=>'-1'},
                              b("Enter reference_no OR pubmed id").br.i("(if more than one, enter in another row)"))).
              td({-align=>'center'},
                        b(font({-size=>'-1'},
                               "Choose Evidence code"))).
                     td({-align=>'center'},
                        font({-size=>'-1'},
                              b("Enter With OR From Association").br.i("(if more than one DB:ID, enter in another row)")))
           );

}

########################################################################
sub printMoreRows {
########################################################################
    my ($self, $num) = @_;
    my $end;
    if ($num >= 5) {
        $end = $num + 2;
    }
    else {
        $end = $num + 7;
    }
    print $self->headerRow;
    for (my $i = $num; $i <= $end; $i++) {
        print Tr(td($self->ontologyField($i)).
                 td($self->goidField($i)).
                 $self->goQualifier($i).
                 td($self->goReferenceField($i)).
                 td($self->goEvidenceField($i)).
                 td($self->goWithFromField($i))),
              $self->locusList4goid($i),
              $self->featureList4goid($i),
              $self->rowSeparator;
    }
}


########################################################################
sub goQualifier {
########################################################################
    my ($self, $i, $isNot, $col_with, $cont_to) = @_;

return qq '
<td>
    <table border="0" cellpadding="0" cellspacing="0" width="10%" height="10%">
  <tr>
    <td align ="bottom">
      <br><br><br><input type="checkbox" name="isNot$i"><font size="2">Not</font>
    </td>
  </tr>
  <tr>
    <td>
    <input type="checkbox" name="col_with$i" ><font size="2">Colocalizes</font></td>
  </tr>
  <tr>
    <td>
    <input type="checkbox" name="cont_to$i"><font size="2">Contributes</font></td>
 </tr>
</table>
</td>
';

#     return table(Tr(td({-align=>'right'},
#                        b(font({-size=>'-1'},
#                               "Colocalizes with"))).
#                     td({-align=>'left'},
#                        textfield(-name=>"col_with$i",
#                                  -value=>"$col_with",
#                                  -size=>'12'))
#                  ).
#                  Tr(td({-align=>'right'},
#                        b(font({-size=>'-1'},
#                               "Contributes to:"))).
#                     td({-align=>'left'},
#                        textfield(-name=>"cont_to$i",
#                                  -value=>"$cont_to",
#                                  -size=>'12'))
#                  )
#            );
#
#
# Tr(td({-align=>'right'},b(font({-size=>'-1'},checkbox(-name=>"isNot$i",-label=>' NOT'))).
#                     td({-align=>'left'},
#                        textfield(-name=>"col_with$i",
#                                  -value=>"$col_with",
#                                  -size=>'12'))
#                  ).

}

########################################################################
sub printNewEntryTitle {
########################################################################
    print "<tr><td colspan=6 align=center BGCOLOR='#a4abc2'><b>Enter New Annotations</b></td></tr>";
}

########################################################################
sub rowSeparator {
########################################################################
    return Tr(td({-colspan=>'6'},
                 hr));

}

########################################################################
sub goidField {
########################################################################
    my ($self, $i, $goid, $goTerm, $isNot) = @_;
    return table(Tr(td({-align=>'left'},
                       b(font({-size=>'-1'},
                              "GO#:"))).
                    td({-align=>'left'},
                       textfield(-name=>"goid$i",
                                 -value=>"$goid",
                                 -size=>'7')
                 )));

}




# ########################################################################
# sub goidField {
# ########################################################################
#     my ($self, $i, $goid, $goTerm, $isNot) = @_;
#     return table(Tr(td({-align=>'left'},
#                        b(font({-size=>'-1'},
#                               "GO#:"))).
#                     td({-align=>'left'},
#                        textfield(-name=>"goid$i",
#                                  -value=>"$goid",
#                                  -size=>'7')
#                  )));
#
# }



1;




