#!/usr/bin/perl
package sdevReservePapers;
#######################################################################
# Script:  sdevReservePapers.pm
# Author : Anand Sethuraman
# Date   : 9th July 2003
#
# This program displays uncurated papers in dictyBase and lets the curators to
# reserve papers.  Other options include disassocating user name from
# reserved paper(s), sorting, and searching.  Once the paper is completely
# curated (including Literature Guide, GO etc), it will not be displayed on this
# interface.
#
# Documentation:
# http:///usr/local/dicty/www_dictybase/db/lib/staff/dictyBase/programmer/program_docs/reserve_papers.html
#######################################################################
use strict;
use DBI;
use CGI qw/:all/;
use CGI::Carp qw(fatalsToBrowser);

use lib "/usr/local/dicty/www_dictybase/db/lib/dictyBase/Objects";
use GeneInfo;
use Reference;
use Locus;
use Feature;
use ConfigURLdictyBase;
use ConfigPathdictyBase;

use lib "/usr/local/dicty/www_dictybase/db/lib/common";
use Login qw (ConnectToDatabase);
use TextUtil qw (DeleteUnwantedChar);

use lib "/usr/local/dicty/www_dictybase/db/lib/dictyBase";
use dictyBaseObject;
use dictyBaseCentralMod qw(:formatPage :navigateInfo);

#######################################################################
#################### global variables #################################
#######################################################################
my $dbh;
my $dblink; 
my $configUrl;
my $configPath;
my %curator4refNo;
my @references;
my $maxDisplayNo = 30;
my $beg = param('beg');
if(!$beg) { $beg = 1; }

###############################################################################
sub new;
sub Destroy;
sub start;
sub update_references_file;
sub displayAllRefs;;

#######################################################################
sub new {   ############ constructor ###############################
#######################################################################
       
	my ($self, %args) = @_;

	$self = {};
	bless $self;

      	$self->{'_database'} = $args{'database'};
	$self->{'_user'}     = $args{'user'};
	$self->{'_title'} = "Curator Reference Reservation Page";
    	return $self;
}

sub database { $_[0]->{_database} }
sub user { $_[0]->{_user} }
sub title { $_[0]->{_title} }

######################################################################
sub DESTROY {   ############ destructor ##############################
######################################################################
    	if (defined $dbh) {
		$dbh->disconnect;
    	}
}

######################################################################
sub start{
######################################################################

    	my ($self) = @_;
	$configPath = ConfigPathdictyBase->new;
	$configUrl = ConfigURLdictyBase->new;
	$dblink = $configUrl->dblink($self->database);
	$dbh = &ConnectToDatabase($self->database);
# before doing anything, update the papers list with new uncurated papers, if any, 
# since the last update;
	update_references_file;
	my $giObject = GeneInfo->new(dbh=>$dbh);
	$self->displayAllRefs($giObject);
	exit;
}

########################################################################
sub update_references_file {
########################################################################
#
# This function updates the references file with new uncurated
# papers, if any, since the last update
###############################################################

# open up the paper list; this tab-delimited file contains two
# columns - reference no and curator name 
# NOTE: curator name is NONE if actually nobody claimed that paper

open(ALLPAPERS, "/share/dictyBase/data/reserve_papers/all_papers.txt") || die
    "Cannot open file /share/dictyBase/data/reserve_papers/all_papers.txt : $!";

while (<ALLPAPERS>) {
    chomp $_;
    my ($ref_no, $curator) = split(/\t/);
    #create the following hashes
    $curator4refNo{$ref_no} = $curator;
} # end of while
close(ALLPAPERS);

# query the database now and look for all new, uncurated papers for the
# previous 7 days from the sysdate; if new ones are found, add it to the 
# hash and re-write the file

my $sth = $dbh->prepare("
                SELECT unique reference_no 
                FROM   CGM_DDB.reference
                WHERE  date_created >= sysdate-14
            ");
eval { $sth->execute(); };
if ($@) {
        print LOG "Error occurred when selecting new uncurated references from the database':\n$@\n\n";
        $sth->finish;
        $dbh->rollback;
        $dbh->disconnect;
        exit;
    }
while (my $refNo = $sth->fetchrow()){
    if (! exists $curator4refNo{$refNo}) {
        $curator4refNo{$refNo} = 'NONE';
    }
}

# after looking for new papers, rewrite the file with the new data
open(UPDATE, ">/share/dictyBase/data/reserve_papers/all_papers.txt") || die
    "Cannot open file /share/dictyBase/data/reserve_papers/all_papers.txt : $!";

foreach my $ref (keys %curator4refNo) {
    print UPDATE "$ref\t$curator4refNo{$ref}\n";
}

close (UPDATE);

}

########################################################################
sub displayAllRefs {
########################################################################
    my ($self, $giObject) = @_;
    &printStartPage($self->database, $self->title);
    print p;
    my $instructions_1;
    $instructions_1 = Tr(td({-align=>'full'}, ("
Curators can use this page to reserve references for curation. By
claiming papers we can avoi d duplication of effort and overwriting a
fellow curator's work. A reservation implies that t he reference will
be fully curated - for all genes, GO, pathways, updating locus pages,
and a ny other curator tasks associated with literature curation.
")));

print start_form, hidden('user', $self->user), 
    table({-align=>'center', 
	   -width=>'95%', 
	   -cellpadding=>'1', 
	   -cellspacing=>'1', 
	   -border=>'0'}, 
	  $instructions_1), end_form;

print p;
my $instructions_2;
$instructions_2 = Tr(td({-align=>'full'}, (ul(li("
To sign up for papers, mark the checkbox in the 'Reservation' column
next to the refe rences you wish to claim.
"),

    li("To remove a reservation, mark the checkbox in the 'Disassociate' column. "),
    li("References will be removed from this list when there are no more 'Not yet curated' tags for the loci associated with the paper.  "),
    li("Unlike the 'References Added this Week' page on the dictyBase home page, this list is not cached and is updated immediately. 
"))))); 
print start_form, hidden('user', $self->user), 
    table({-align=>'center', 
	   -width=>'95%', 
	   -cellpadding=>'1', 
	   -cellspacing=>'1', 
	   -border=>'0'}, $instructions_2), end_form;

    my $url = $configUrl->dictyBaseCGIRoot. "dictyBaseDEV/curation/reserve_papers.pl?user=$self->user";
    my $navigationBar = $self->displayNavigationBar;
    print "<a name='top'>";
    print table({-border=>'0',
		 -width=>'100%'},   
		Tr(td(&ResultPageList(url=>$url,
				  totalHit=>83,
				  showNum=>$maxDisplayNo,
				  beg=>$beg))).
		Tr(td($navigationBar)).
		Tr(td(table({-align=>'center',
			     -border=>'0',
			     -cellpadding=>'3',
			     -cellspacing=>'3',
			     -width=>'100%'},
                        Tr(th({-align=>'left',
                               -bgcolor=>'#a4abc2'},
                              "Reservation").
                           th({-align=>'left',
                               -bgcolor=>'#a4abc2'},
                              "Disassociate").
                           th({-align=>'left',
                               -bgcolor=>'#a4abc2'},
                              "Date Added to dictyBase").
			   th({-align=>'left',
			       -bgcolor=>'#a4abc2'},
			      "Reference").
			   th({-align=>'left',
			       -bgcolor=>'#a4abc2'},
			      "Other Genes Addressed"))))));
    print "<a name='bot'>";
    &printEndPage;
}

########################################################################
sub displayNavigationBar {
########################################################################
    my ($self)= @_;
    my $end = 40;
    if ($end <= $maxDisplayNo) { return;}
    my $beg = 1;
    my $matchNum = $self->{'_matchNum'};
    my $stop = $self->{'_stop'};
    my $skipRow = $self->{'_skipRow'};
    if (!$stop) { $stop = $end;}
    if ($beg < $skipRow + 1) { 
    	$beg = $skipRow + 1; 
    }
    if ($stop < $skipRow + 30) {
    	$stop += $skipRow + 1;
    }
    my $navigationBar;
       
    if (!$beg) { $beg = 1; }
    my ($prevBeg, $nextBeg);
    if ($end > $stop+1) {
	$nextBeg = $stop+1;
    }
    if ($beg > 1) {
	$prevBeg = $beg - $maxDisplayNo;
	if ($prevBeg < 1) { $prevBeg = 1;}
    }
    my $id = param('id');
    if (!$id) { $id = $$; }
    my $filterBy = param('filterBy');
    my $sortedBy = param('sortedBy');
    my $searchFor = param('searchFor');
#    my $navigationListRef = $self->{'_navigationList'};
#    my @listItem = @$navigationListRef;
    my @listItem = ("2003");
    my @sortColumn = ("Citation", "Year");
    my $topic = param('topic');
    $topic =~ s/ /\+/g;
    my $url = $configUrl->dictyBaseCGIRoot. "dictyBaseDEV/curation/reserve_papers.pl?user=$self->user";
    if (param('date')) {
	$url .= "&date=1";
    }
    my $nextPrevUrl = $url;
    if ($filterBy) {
	$filterBy =~ s/ /\+/g;
	$searchFor =~ s/ /\+/g;
	$nextPrevUrl .= "&searchFor=$searchFor&filterBy=$filterBy";	    
    }
    elsif ($sortedBy) {
	$sortedBy =~ s/ /\+/g;
	$nextPrevUrl .= "&sortedBy=$sortedBy";
    }
    $navigationBar =  &navigationBar(database=>$self->database,
				     url=>$url,
				     nextPrevUrl=>$nextPrevUrl,
				     beg=>$beg,
				     nextBeg=>$nextBeg,
				     prevBeg=>$prevBeg,
				     downloadfile=>"geneinfo.$id.xls",
				     navigateListRef=>\@listItem,
				     sortListRef=>\@sortColumn,
				     pos=>'top'), br;
    
    return $navigationBar;
}

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