#!/usr/bin/perl
use DBI;
require "config.pl";
$localtime = localtime(time);
open LOG, ">>$LogFile";
print LOG "#----------- Daily Check $localtime\n"; 
$time = time - 5*3600; 
@date =  gmtime($time); # Get present EST time ( GMT - Time Lag)
if($date[2] < 12){ # In case of AM, use previous day's records
	$time -= 12*3600;
	@date = gmtime($time);
}
$year = $date[5]+1900;
$month = $date[4]+1;
$day = $date[3];
print LOG "EST Time : $year/$month/$day:$date[2]:$date[1]:$date[0]\n";
if($month < 10){
	$month = "0".$month;
}
if($day < 10){
	$day = "0".$day;
}
$today = "$year-$month-$day";
$today_file = "$year$month$day.txt";
close LOG;
system("perl get_daily.pl $year/$month/$day");
open LOG, ">>$LogFile";
if(! -s ("temp/$today_file")){
	print LOG "No New Records\n";
	close LOG;
	exit;
}
$dns = "DBI:mysql:$mysql_db:$mysql_host";
$dbh = DBI-> connect($dns,$mysql_user,$mysql_pwd);
$sth = $dbh -> prepare("select u_id,u_pick_num,u_mail_type,u_mail from user");
$sth -> execute();
while (@user = $sth -> fetchrow_array()){
	print LOG "Start for $user[0]\n";
	system("perl calc_score.pl $user[0] $today_file");
	open IN, "temp/$user[0].$today_file.score.txt";
	%score = ();
	while (<IN>){
		chomp;
		split(/\t/);
		$score{$_[1]} = $_[-1];
	}
	close IN;
	@keys = sort {$score{$b} <=> $score{$a}} keys(%score);
	%hit = ();
	for($i=0;$i<$user[1];$i++){
		$sth2 = $dbh -> prepare("insert into hit set h_uid = '$user[0]', h_pmid='$keys[$i]', h_date = '$today',h_score = '$score{$keys[$i]}'");
		$sth2 -> execute();
		$hit{$keys[$i]} = 1;
	}
	open IN, "temp/$today_file";
	%data = ();
	while (<IN>){
		if(/^PMID-\s+(\d+)/){
			$pmid = $1;
			if($hit{$1}){
				$hit_flag = 1;
				$data{$pmid}->{'full'} .= $_;
			}
			else{
				$hit_flag = 0;
			}
		}
		elsif($hit_flag){
			$data{$pmid}->{'full'} .= $_;
			if(/^\n/ and $pmid){
				$pmid = "";
				$hit_flag = "";
			}
			if(/^(AB|TI|AD|AU|SO)\s+\-\s+(.+)/){
				$field = $1;
				if($field eq "AU"){
					$tmp = $2;
					chomp($tmp);
					$data{$pmid}->{$field} .= "$tmp, ";
				}
				else{
					$data{$pmid}->{$field} = "$2\n";
				}
			}
			elsif(/^[A-Z]+/){
				$field = "";
			}
			elsif($field){
				s/^\s+//;
				$data{$pmid}->{$field} .= $_;
			}
		}
	}
	close IN;
	$key_flag = 0;
	while (!$key_flag){
		$daylink = int(rand(1000000000));
		$sth2 = $dbh -> prepare("select * from daylink where d_id = '$daylink'");
		$sth2 -> execute();
		if(!$sth2->rows()){
			$key_flag = 1;
		}
	}
	$sth2 = $dbh -> prepare("insert into daylink set d_id = '$daylink',d_date = '$today',d_uid = '$user[0]'");
	$sth2 -> execute();
	print LOG "DAY LINK Key: $daylink\n";
	open(OUT,"| $sendmail -t -i") || die 'sendmail error';
	print OUT "From: PURE_SYSTEM\@$ENV{HOSTNAME}\n";
	print OUT  "To: $user[3]\n";
	print OUT "Subject: PURE Daily Mail\n";
	print OUT "Content-Transfer-Encoding: 7bit\n";
	print OUT "Content-Type: text/html;\n\n";
	print OUT "<HTML><BODY><PRE>\n";
	print OUT "<a href = '$pure_url?daylink=$daylink'>Go To PURE</A>\n";
	for($i=0;$i<$user[1];$i++){
		$score{$keys[$i]} = int(($score{$keys[$i]}+0.005)*100)/100;
		print OUT "PMID: <a href = '$pure_url?daylink=$daylink&pmid=$keys[$i]'>$keys[$i]</a>, SCORE: $score{$keys[$i]}\n";
		print OUT "$data{$keys[$i]}->{TI}\n";
		$data{$keys[$i]}->{'AU'} =~ s/\, $//;
		print OUT "$data{$keys[$i]}->{AU}\n";
		print OUT "$data{$keys[$i]}->{AD}";
		print OUT "$data{$keys[$i]}->{SO}\n";
		if($user[2] eq 'Title+Abstract'){
			print OUT "$data{$keys[$i]}->{AB}\n";
		}
		print OUT "\n";
		$full = $dbh->quote($data{$keys[$i]}->{'full'});
		$sql = "insert into pubmed set p_pmid = $keys[$i], p_full = $full";
		$sth2 = $dbh -> prepare($sql);
		$sth2 -> execute();
	}
	print OUT "<a href = '$pure_url?daylink=$daylink'>Go To PURE</A>\n";
	print OUT "</PRE></BODY></HTML>\n";
	close OUT;
	unlink("temp/$user[0].$today_file.score.txt");
	
}
unlink("temp/$today_file");
#---------------- Delete Expired Records ---------------
$time = time - $expire*24*3600;
@date = localtime($time);
$year = $date[5]+1900;
$month = $date[4]+1;
$day = $date[3];
$limit = "$year-$month-$day";
$sth = $dbh -> prepare("delete from daylink where d_date < '$limit'");
$sth -> execute();
$sth = $dbh -> prepare("select h_pmid from hit where h_date < '$limit'");
$sth -> execute();
$c = 0;
while (@data = $sth -> fetchrow_array()){
	$sth2 = $dbh -> prepare("delete from pubmed where p_pmid = '$data[0]'");
	$sth2 -> execute();
	$sth2 = $dbh -> prepare("delete from hit where h_pmid = '$data[0]'");
	$sth2 -> execute();
	$c++;
}
print LOG "$c Records, before $limit, are deleted.\n";
close LOG;
exit;
