package GeneInfoUserPage;

##########################################################
#                                                        #
# dictyBase Extension of GeneInfoUserPage                #
#                                                        #
##########################################################

use GeneInfoUserPage_base;

BEGIN { %GeneInfoUserPage:: = %GeneInfoUserPage_base:: }

use Locus;

#
#  changed search to include aliases aslo took out "discoideum"
#
########################################################################
sub pubmedSearch {
########################################################################
    my ($self) = @_;
    my $locusObj =  Locus->new(dbh=>$dbh,
                                      locus_name=>$self->locus);
    return Tr(td(a({-href=>$configUrl->ncbiUrlRoot."query.fcgi?cmd=search&db=PubMed&term=%28".$locusObj->searchString."%5bTEXT%3anoexp%5d%20AND%20Dictyostelium%5bALL%5d%29",
                    -target=>'infowin'},
                   "PubMed Search"))).
           Tr(td(a({-href=>$configUrl->ncbiUrlRoot."query.fcgi?cmd=search&db=PubMed&term=%28".$locusObj->searchString."%5bALL%5d%20AND%20Dictyostelium%5bALL%5d%29",
                    -target=>'infowin'},
                   "Expanded PubMed Search"))) if ($locusObj);
}


########################################################################
sub displayLoci {
########################################################################
    my ($self, $giObject) = @_;
    &printStartPage($self->database, $self->title, $self->help);
    my $geneNum = $giObject->geneNum;
    print table({-align=>'center',
                 -valign=>'top',
                 -cellpadding=>'4'},
                 Tr(td({-bgcolor=>"#b7d8e4"},
                               a({-href=>"/db/cgi-bin/dictyBase/reference/geneinfo.pl?locus=".$self->locus},
                                 $self->locus." Literature Topics")).
                    td({-bgcolor=>"#b7d8e4"},
                               a({-href=>$configUrl->dictyBaseCGIRoot."gene_page.pl?gene_name=".$self->locus},
                               $self->locus." Locus Info"))));

    print table({-align=>'center',
                 -valign=>'top'},
                 Tr(td(h2(font({-color=>'red'}, $geneNum)." other genes are mentioned in papers curated for ".$self->locus))));

    my $arrayRef4locus = $giObject->locusList;
#
#
#  dictyBase simply took out next two lines
#   we don't want to display the feature names, just the loci
#
#    my $arrayRef4feat = $giObject->featureList;
#    push (@$arrayRef4locus, @$arrayRef4feat);
    my $tableList;
    my (@rows, @tables, @tableLabels, %geneLabel);
    my ($geneNo, $i, $colNum, $begGene, $preGene);
    my ($labelBeg, $labelEnd, $label);
    foreach my $rowRef (@$arrayRef4locus) {
            my ($gene) = @$rowRef;
            if (uc($gene) eq uc($self->locus)) { next; }
            $i++;
            $geneNo++;
            $geneLabel{$geneNo} = $gene;
            if ($i > 20) {
                $colNum++;
                unshift(@rows, td("${begGene}-${preGene}"));
                $tableList .= td(table({-align=>'center',
                                        -valign=>'top',
                                        -cellspacing=>'3',
                                        -cellpadding=>'3',
                                        -border=>'1'},
                                       Tr({-align=>'center'},\@rows)));

                undef @rows;
                $i = 1;
                $begGene = $gene;
            }
            if ($colNum == 5) {
                $labelBeg = $geneNo - 100;
                $labelEnd = $geneNo - 1;
                $label = "${labelBeg}-$labelEnd";
                push(@tableLabels, "${label}($geneLabel{$labelBeg}-$geneLabel{$labelEnd})");
                my $table= table({-align=>'center',
                                  -valign=>'top'},
                                 Tr(th({-colspan=>'5',
                                        -bgcolor=>"#869FB6",
                                        -align=>'center'},
                                       font({-size=>'+1'}, $label))).
                                 Tr($tableList));
                push(@tables, $table);
                undef $tableList;
                undef $colNum;
            }
            if ($i == 1) {
                $begGene = $gene;
            }
            push(@rows, td(a({-href=>$configUrl->dictyBaseCGIRoot."gene_page.pl?gene_name=$gene", -target=>'infowin'},$gene)));
            $preGene = $gene;
    }
    unshift(@rows, td("${begGene}-${preGene}"));
    $tableList .= td({-align=>'center',
                      -valign=>'top'},
                     table({-align=>'center',
                            -valign=>'top',
                            -cellspacing=>'3',
                            -cellpadding=>'3',
                            -border=>'1'},
                           Tr({-align=>'center'},\@rows)));

    my $labelBeg = $labelEnd + 1;
    my $label = "${labelBeg}-$geneNo";
    push(@tableLabels, "${label}($geneLabel{$labelBeg}-$geneLabel{$geneNo})");
    my $table= table({-align=>'center',
                      -valign=>'top'},
                     Tr(th({-colspan=>'5',
                            -bgcolor=>"#869FB6",
                            -align=>'center'},
                           font({-size=>'+1'}, $label))).
                     Tr($tableList));
    push(@tables, $table);
    my $popup = table({-align=>'center'},
                      Tr(td(b(font({-size=>'+1'}, "Jump to: "))).
                         td(start_form).
                         td(popup_menu(-name=>'jumpItem',
                                       -"values"=>\@tableLabels,
                                       -onchange=>'jump(this)')).
                         td(end_form)));
    for(my $i = 0; $i <= @tables; $i++) {
        print "<a name='$tableLabels[$i]'>";
        if ($geneNum > 100) {
            print $popup;
        }
        print $tables[$i];
    }

    my $maxCuratedDate = $giObject->maxCuratedDate;
    my $maxPubmedSearchDate = $giObject->maxPubmedSearchDate;

    print br.br.table({-align=>'center'},
                      Tr(td(b("Date of last curation:")).
                         td($maxCuratedDate).
                         td(b("Date of last PubMed Search:")).
                         td($maxPubmedSearchDate)
                         ));

   &printEndPage;
}


#
# took out feature list for now
#
########################################################################
sub references4topic {
########################################################################
    my ($self, $giObject, $all) = @_;

    my $arrayRef;
    if ($all) {
        $arrayRef = $giObject->topicInfo;
    }
    elsif (param('topic') =~ /\:/) {
        my @topic = split(/\:/, param('topic'));
        foreach my $topic (@topic) {
            $self->{'_title'} .= $topic.", ";
            if (!$arrayRef) {
                $arrayRef = $giObject->topicInfo($topic);
            }
            else {
                my $thisArrayRef =  $giObject->topicInfo($topic);
                push(@$arrayRef, @$thisArrayRef);
            }
        }
        $self->{'_title'} =~ s/, $//;
    }
    else {
        if (!$self->locus) {
            $self->{'_title'} .= param('topic');
        }
        $arrayRef = $giObject->topicInfo(param('topic'));
    }

    my $end = @$arrayRef;
    my (@refs, %tmp);
    if (param('sortedBy') =~ /citation/i) {
        foreach my $rowRef (@$arrayRef) {
            my ($refNo, $citation, $year, $pubmed, $journal) = @$rowRef;
            $tmp{$citation} = $refNo."\t".$year."\t".$pubmed."\t".$journal;
        }
        foreach my $citation (sort (keys %tmp) ) {
            my ($refNo, $year, $pubmed, $journal) =
                split(/\t/, $tmp{$citation});
            my @row = ($refNo, $citation, $year);
            my $rowRef = \@row;
            push(@refs, $rowRef);
        }
    }
    elsif (!$self->locus) {
        my @tmpRefs;
        foreach my $rowRef (@$arrayRef) {
            my ($refNo, $citation, $year, $pubmed, $journal) = @$rowRef;
            if ($tmp{$year}) { $tmp{$year} .= "::"; }
            $tmp{$year} .= $refNo."\t".$citation."\t".$pubmed."\t".$journal;
        }
        foreach my $year (sort{$a<=>$b} (keys %tmp) ) {
            my @entry = split(/::/, $tmp{$year});
            foreach my $entry (@entry) {
                my ($refNo, $citation, $pubmed, $journal) =
                    split(/\t/, $entry);
                my @row = ($refNo, $citation, $year, $pubmed, $journal);
                my $rowRef = \@row;
                push(@tmpRefs, $rowRef);
            }
        }
        @refs = reverse (@tmpRefs);
    }
    else {
        @refs = reverse (@$arrayRef);
    }

    my $returnList;
    my $bgcolor;
    my $beg = param('beg');
    if (!$beg) { $beg = 1; }
    my $matchYear;
    if (param('navigateList') =~ /^Year ([0-9]+)$/i) {
        $matchYear = $1;
    }
    if (!param('id')) {
        open(OUT, ">$downloadfile") ||
            die "Can't open '$downloadfile' for writing:$!\n";
        print OUT "Citation\tLoci\n\n";
    }
    my $searchFor = param('searchFor');
    my $filterBy = param('filterBy');
    my ($num, $skipRow, $stop, $matchNum);
    my @navigationList;
    my %year;

    my ($locusNm4RefNoHashRef, $featNm4RefNoHashRef, $url4RefNoHashRef);
    my ($relatedRefInfo4RefNoHashRef, $webSupplementUrl4RefNOHashRef);

    if (!$self->locus && @refs > 100) {
        $locusNm4RefNoHashRef = $giObject->getLocusNm4RefNoHashRef;
        $featNm4RefNoHashRef = $giObject->getFeatNm4RefNoHashRef;
        $url4RefNoHashRef = $giObject->getUrl4RefNoHashRef;
        $relatedRefInfo4RefNoHashRef
            = $giObject->getRelatedRefInfo4RefNoHashRef;
        $webSupplementUrl4RefNOHashRef
            = $giObject->getWebSupplementUrl4RefNoHashRef;
    }

    my %foundRef;
    foreach my $rowRef (@refs) {
        my ($refNo, $ORIcitation, $year, $pubmed, $journal) = @$rowRef;
        if ($foundRef{$refNo}) {
            $end--;
            next;
        }
        $foundRef{$refNo}++;
        $year{$year}++;
        if ($matchYear && $matchYear < $year) {
            $skipRow++;
            next;
        }
        if ($filterBy) {
            if ($searchFor =~ /citation/i &&
                $ORIcitation !~ /$filterBy/i) {
                next;
            }
            elsif ($searchFor =~ /year/i &&
                   $year !~ /$filterBy/i) {
                next;
            }

        }
        my ($citation, $locusList, $featureList);
        if (!$self->locus && @refs > 100) {
            my $urls = $$url4RefNoHashRef{$refNo};
            my $relatedRefInfo = $$relatedRefInfo4RefNoHashRef{$refNo};
            my $webSuppUrl = $$webSupplementUrl4RefNOHashRef{$refNo};
            $citation = $self->citation2($refNo, $ORIcitation, $pubmed,
                                         $journal, $urls,
                                         $relatedRefInfo, $webSuppUrl);
            $locusList = $$locusNm4RefNoHashRef{$refNo};
            $featureList = $$featNm4RefNoHashRef{$refNo};
        }
        else {
            my $refObject;
            ($citation, $refObject) = $self->citation($refNo);
            foreach my $rowRef (@{$refObject->locusArrayRef}) {
                my ($locusNm) = @$rowRef;
                $locusList .= $locusNm."\t";
            }

            $locusList =~ s/\t$//;
#            foreach my $rowRef (@{$refObject->featureArrayRef}) {
#                my ($featNm) = @$rowRef;
#                $featureList .= $featNm."\t";
#            }
            $featureList =~ s/\t$//;
        }

        my $loci;
        if ($locusList && $featureList) {
            $loci = $locusList."\t".$featureList;
        }
        elsif ($locusList) { $loci = $locusList; }
        elsif ($featureList) { $loci = $featureList; }

        $loci =~ s/^\t//;
        $loci =~ s/\t$//;
        my @loci = split(/\t/, $loci);
        if (!param('id')) {
            print OUT "$ORIcitation\t@loci\n";
        }
        $num++;
        if ($num < $beg) { next; }
        if ($num >= $beg + $maxDisplayNo && !param('id')) {
            if (!$stop) { $stop = $num - 1; }
            next;
        }
        elsif ($num >= $beg + $maxDisplayNo && param('id')) {
            if (!$stop) {$stop = $num - 1;}
            next;
        }
        my $listLoci;
        my $i;
        foreach my $locus (@loci) {
            if ($self->locus && $self->locus =~ /^$locus$/i) {
                next;
            }
            $i++;
            if ($i > 15) { last; }
            if ($i == 15) {
                $listLoci .= " |".a({-href=>$configUrl->dictyBaseCGIRoot."$dblink/reference/reference.pl?refNo=$refNo#summary", -target=>'infowin'}, font({-color=>'red'}, "MORE"));
            }
            else {
                $listLoci .= " |".a({-href=>$configUrl->dictyBaseCGIRoot."gene_page.pl?gene_name=$locus", -target=>'infowin'}, $locus);
            }
        }
        $listLoci =~ s/^\|//;
        if (!$listLoci) { $listLoci = br; }
        if (!$bgcolor) {
            $returnList .= Tr(td({-width=>"70%",
                                  -valign=>"top"},
                                 $citation).
                              td({-width=>"30%",
                                  -valign=>"top"},
                                 $listLoci));
            $bgcolor = "#d8d8d8";
        }
        else {
            $returnList .= Tr({-bgcolor=>"$bgcolor"},
                              td({-width=>"70%",
                                  -valign=>"top"},
                                 $citation).
                              td({-width=>"30%",
                                  -valign=>"top"},
                                 $listLoci));
            $bgcolor = "";
        }
        $matchNum++;
    }
    $self->{'_end'} = $end;
    if (!param('id')) { close(OUT); }
    foreach my $year (sort {$a<=>$b;} keys %year ) {
        push(@navigationList, "Year $year");
    }
    $self->{'_skipRow'} = $skipRow;
    $self->{'_stop'} = $stop;
    $self->{'_matchNum'} = $matchNum;
    $self->{'_navigationList'} = \@navigationList;
    return $returnList ;
}

#
#
# changed order of sections, added development section
#
########################################################################
sub topicsSection {
########################################################################
    my ($self, $giObject) = @_;
    return table({-width=>'100%',
                  -cellpadding=>'0',
                  -cellspacing=>'0'},
                 Tr(td({-bgcolor=>'#d8d8d8',
                        -align=>'left',
                        -valign=>'center'},
                       h4(a({-href=>$configUrl->dictyBaseCGIRoot."gene_page.pl?gene_name=".$self->locus}, $self->locus).
                          font({-color=>'black'}, " LITERATURE TOPICS")
                       ))).
                 $self->geneticsCellBiol($giObject).
                 $self->lifeCycle($giObject).
                 $self->nucleicAcidInfo($giObject).
                 $self->proteinInfo($giObject).
                 $self->relatedGenesProteins($giObject).
                 $self->researchAids($giObject).
                 $self->curatedLiterature($giObject).
                 $self->additionalInfo($giObject)
            );

}



########################################################################
sub geneticsCellBiol {
########################################################################
    my ($self, $giObject) = @_;

    my $returnTopics;

    $returnTopics .= $self->topicEntry($giObject->hasMutantsPhenotypes,
                                       "Mutants/Phenotypes");
    $returnTopics .= $self->topicEntry($giObject->hasFunctionProcess,
                                       "Function/Process");
    $returnTopics .= $self->topicEntry($giObject->hasCellularLocation,
                                         "Cellular Location");
    $returnTopics .= $self->topicEntry($giObject->hasCytoskeleton,
                                         "Cytoskeleton");
    $returnTopics .= $self->topicEntry($giObject->hasChemotaxis,
                                         "Chemotaxis/Motility");
    $returnTopics .= $self->topicEntry($giObject->hasMitosis,
                                         "Mitosis");
    $returnTopics .= $self->topicEntry($giObject->hasEndocytosis,
                                       "Endocytosis");
    $returnTopics .= $self->topicEntry($giObject->hasAdhesion,
                                       "Adhesion");
    $returnTopics .= $self->topicEntry($giObject->hasSignalTransduction,
                                       "Signal Transduction");
    $returnTopics .= $self->topicEntry($giObject->hasCellCycle,
                                       "Cell Cycle");
    $returnTopics .= $self->topicEntry($giObject->hasGeneticInteractions,
                                       "Genetic Interactions");
    $returnTopics .= $self->topicEntry($giObject->hasPhototaxis,
                                       "Phototaxis/Thermotaxis");
    if ($returnTopics) {
        $returnTopics = Tr(td({-bgcolor=>"#869FB6"},
                           b("Genetics/Cell Biology"))).ul($returnTopics);
    }
    return $returnTopics;
}




########################################################################
sub lifeCycle {
########################################################################
    my ($self, $giObject) = @_;

    my $returnTopics;

    $returnTopics .= $self->topicEntry($giObject->hasGrowth,
                                       "Growth");
    $returnTopics .= $self->topicEntry($giObject->hasMorphogenesis,
                                       "Development/Morphogenesis");
    $returnTopics .= $self->topicEntry($giObject->hasGermination,
                                         "Sporulation/Germination");
    $returnTopics .= $self->topicEntry($giObject->hasSexualCycle,
                                         "Sexual Cycle");
    $returnTopics .= $self->topicEntry($giObject->hasCellTypeLocalization,
                                         "Cell Type Localization");

    if ($returnTopics) {
        $returnTopics = Tr(td({-bgcolor=>"#869FB6"},
                           b("Life Cycle"))).ul($returnTopics);
    }
    return $returnTopics;
}

########################################################################
sub nucleicAcidInfo {
########################################################################
    my ($self, $giObject) = @_;
    my $returnTopics;


    $returnTopics .= $self->topicEntry($giObject->hasDnaRnaSequenceFeatures,
                                         "DNA/RNA Sequence Features");
    $returnTopics .= $self->topicEntry($giObject->hasMapping,
                                       "Mapping");
    $returnTopics .= $self->topicEntry($giObject->hasRnaLevelsAndProcessing,
                                       "RNA Levels and Processing");
    $returnTopics .= $self->topicEntry($giObject->hasTranscription,
                                       "Transcriptional Regulation");
    $returnTopics .= $self->topicEntry($giObject->hasTranslationalRegulation,
                                       "Translational Regulation");


    if ($returnTopics) {
        $returnTopics = Tr(td({-bgcolor=>"#869FB6"},
                           b("Nucleic Acid Information"))).ul($returnTopics);
    }
    return $returnTopics;
}


########################################################################
sub relatedGenesProteins {
########################################################################
    my ($self, $giObject) = @_;
    my $returnTopics;



    $returnTopics .= $self->topicEntry($giObject->hasDiseaseRelated,
                                       "Disease Related");
    $returnTopics .= $self->topicEntry($giObject->hasNonMammalianRelatedGenes,
                                       "Non-mammalian Gene Related");
    $returnTopics .= $self->topicEntry($giObject->hasMammalianRelatedGenes,
                                       "Mammalian Gene Related");
    $returnTopics .= $self->topicEntry($giObject->hasPhylogeneticAnalysis,
                                       "Phylogenetic Analysis");


    if ($returnTopics) {
        $returnTopics = Tr(td({-bgcolor=>"#869FB6"},
                           b("Related Genes/Proteins"))).ul($returnTopics);
    }
    return $returnTopics;
}

########################################################################
sub proteinInfo {
########################################################################
    my ($self, $giObject) = @_;
    my $returnTopics;


    $returnTopics .= $self->topicEntry($giObject->hasProteinNucleicAcidInteractions,
                                       "Protein-Nucleic Acid Interactions");
    $returnTopics .= $self->topicEntry($giObject->hasProteinPhysicalProperties,
                                      "Protein Physical Properties");
    $returnTopics .= $self->topicEntry($giObject->hasPosttranslational,
                                      "Post-Translational Modifications");
    $returnTopics .= $self->topicEntry($giObject->hasProteinProteinInteractions,
                                       "Protein-Protein Interactions");
    $returnTopics .= $self->topicEntry($giObject->hasProteinNucleicAcidStructure,
                                      "Protein/Nucleic Acid Structure");
    $returnTopics .= $self->topicEntry($giObject->hasSubstratesLigandsCofactors,
                                      "Substrates/Ligands/Cofactors");
    $returnTopics .= $self->topicEntry($giObject->hasProteinFunctionalDomain,
                                      "Protein Functional Domain");
    $returnTopics .= $self->topicEntry($giObject->hasRegulatedBy,
                                                   "Regulated by");
    $returnTopics .= $self->topicEntry($giObject->hasRegulatoryRole,
                                                   "Regulatory Role");

    if ($returnTopics) {
        $returnTopics = Tr(td({-bgcolor=>"#869FB6"},
                           b("Protein Information"))).ul($returnTopics);
    }
    return $returnTopics;
}

#
# changed some
#
########################################################################
sub curatedLiterature {
########################################################################
    my ($self, $giObject) = @_;
    my $returnTopics = $self->topicEntry($giObject->hasSelectedReview,
                                          "Selected Review");
    $returnTopics .= $self->topicEntry($giObject->hasReviews,
                                           "Reviews");
    $returnTopics .= $self->topicEntry($giObject->hasCurated,
                           "List of all Curated References", "curated");
    if ($returnTopics) {
        $returnTopics = Tr(td({-bgcolor=>"#869FB6"},
                           b("Curated Literature"))).ul($returnTopics);
    }
    return $returnTopics;
}


#
# change 'Alias' to synonym
#
########################################################################
sub researchAids {
########################################################################
    my ($self, $giObject) = @_;
    my $returnTopics = $self->topicEntry($giObject->hasSynonym,
                                          "Synonym");
    $returnTopics .= $self->topicEntry($giObject->hasOtherFeatures,
                                           "Other Features");
    $returnTopics .= $self->topicEntry($giObject->hasStrainsConstructs,
                                           "Strains/Constructs");
    $returnTopics .= $self->topicEntry($giObject->hasTechniquesAndReagents,
                                           "Techniques and Reagents");
    $returnTopics .= $self->topicEntry($giObject->hasGenomeWideAnalysis,
                                           "Genome-wide Analysis");
    $returnTopics .= $self->topicEntry($giObject->hasAntibodies,
                                           "Antibodies");
    if ($returnTopics) {
        $returnTopics = Tr(td({-bgcolor=>"#a4abc2"},
                           b("Research Aids"))).ul($returnTopics);
    }
    return $returnTopics;
}


#
# take out call to isMultiple in dictyBaseObject.  This method is broken after Chado
#
#
######################################################################
sub start{
######################################################################

            my ($self) = @_;
        $configPath = ConfigPathdictyBase->new;
        $configUrl = ConfigURLdictyBase->new;
        $dblink = $configUrl->dblink($self->database);
        $self->setDownloadfile;
        my $locus = $self->{'_locus'};
        &DeleteUnwantedChar(\$locus);
        $self->{'_locus'} = $locus;

        $dbh = &ConnectToDatabase($self->database);

        if (!$self->locus) {
            if((!param('topic')) && (!param('date'))) {
                $self->{'_title'} = "Gene Info Search";
                $self->printEntryForm;
            }
            elsif (param('date')) {
                $dbh = &ConnectToDatabase($self->database);
                $self->displayAllRefsThisDate;
            }
            else {
                $dbh = &ConnectToDatabase($self->database);
                $self->displayAllRefs4topics;
            }
            exit;
        }
        if ($self->locus =~ /\*/ || $self->locus =~ /\%/) {
            $dbh = &ConnectToDatabase($self->database);
            my @loci = $self->getGeneList;
            if (@loci > 1) {
                $self->displayGeneList(@loci);
                exit;
            }
            elsif (!@loci) {
                $self->err_report("The locus/feature you entered is not found in database. Please correct it and try again.");
                exit;
            }
            else {
                $self->{'_locus'} = $loci[0];
            }
        }
        elsif (!param('topic')) {

         my $locus_obj = new Locus( dbh=>$dbh, locus_name => $self->locus );

            if ($locus_obj) {
                $self->{'_locus'} = $self->locus;
            }
            else {
                $self->err_report("The gene you entered is not found in database. Please correct it and try again.");
                exit;
            }
        }

        $self->{'_title'} = $self->locus." Literature Guide";
        my $giObject = GeneInfo->new(dbh=>$dbh,
                                     locus=>$self->locus);
        if (param('topic')) {
            $self->displayRef4topic($giObject);
        }
        #elsif (param('date')) {
            #$self->displayAllRefsThisDate($giObject);
        #}
        elsif (param('type')) {
            $self->displayLoci($giObject);
        }
        else {
            $self->displaySummary($giObject);
        }
        exit;

}


########################################################################
1;
########################################################################


















