#!/usr/bin/perl
## LAST UPDATE
### Tue, Mar 22, 2011 @ 15:40:21 EDT
#  for i in enceladus narvi  ; do echo $i; scp /www/odev/htdocs/theme/opals/record/searchform.inc $i:/www/odev/htdocs/theme/opals/record/; scp /www/odev/bin/sessionHdl $i:/www/odev/bin/; scp /www/odev/htdocs/js/ajax.js $i:/www/odev/htdocs/js/ ; done
#

#use utf8;
use strict;
use CGI;

use Opals::Context;
use Opals::Template qw(
    tmpl_read
    tmpl_write
);
use Opals::User qw(
    user_getInformationById
);
use Opals::Session qw(
    SessionHdl_clearVar
    SessionHdl_get
);
use Opals::Locale qw(
    loc_getMsgFile
    loc_write
);
use Opals::SolrIndex qw(
    slr_buildSearchQuery_ARL
    slr_search
    slr_getSuggestion
    slr_getARLMinMax_fieldVal
    slr_getLexileMinMax
);
my $dbh = Opals::Context->dbh();
END { $dbh->disconnect(); }

my $cgi = CGI->new;
my $input = $cgi->Vars();
my ($permission, $cookie, $template) = tmpl_read(
        {
            dbh             => $dbh,
            cgi             => $cgi,
            tmplFile        => 'record/export.tmpl',
            reqPermission   => 'marc_edit|marc_export',
        }
);

my $zid = 0;
my $eType         = $input->{'eType'};
my $eEncoding     = $input->{'eEncoding'};
my ($eFrom, $eTo) = ($input->{'eFrom'}, $input->{'eTo'});
#Mon, Sep 23, 2013 @ 10:42:42 EDT
#
my $exclRecFormat ="";

if ($eType !~ m/^hitlist$/i) {
    my @exclRecFormat= $cgi->param('exclRecFormat');
    $exclRecFormat =join(",",@exclRecFormat);
}


#
my $ridList="";
my $ssid = $cgi->cookie('globalSessionID');
$template->param(hlpUrl     => Opals::Constant->getHlpUrl('export') );

    $template->param(export=>1);
if ((($eFrom && $eTo) || $eType eq 'hitlist') && $ENV{'REQUEST_METHOD'} =~ m/post/i) {   
    my $exporting = isExporting($dbh);
   
  
    if ($exporting) {
        $template->param(
            exporting => 1,
        );
    }
    else {
        my $uid = $template->param('curUserId');

        my $query = <<_STH_;
insert into opl_marcExport
set     uid             = $uid,
        dateRequest     = now(),
        eType           = ?,
        eEncoding       = ?,
        exclRecFormat   ='$exclRecFormat',
        dateExpiry      = now() + interval 30 day,
_STH_

        if ($eType =~ m/^date$|^modDate_r$/i) {
            $query .= <<_STH_;
            eFrom       = date_format('$eFrom', '%Y-%m-%d %H:%i:%S'),
            eTo         = date_format('$eTo', '%Y-%m-%d %H:%i:%S'),
            ridList     = ""
_STH_

       }
       elsif ($eType =~ m/^hitlist$/i) {
            my $rArr = SessionHdl_get($dbh,$ssid,"exp_rid");
            foreach my $r(@$rArr){
                $ridList .= $r->{'rid'} . ",";
            }
            $ridList =~ s/,$//g;
            $eType ='ridList_r';
            $query .= <<_STH_;
            eFrom       = '',
            eTo         = '',
            ridList     = '$ridList'
_STH_

          }
        elsif ($eType =~ m/^rid$/i) {
            $query .= <<_STH_;
                eFrom       = '$eFrom',
                eTo         = '$eTo'
     
_STH_
        }
        else {
            $query =~ s/,$//;
        }
        
         my $sth = $dbh->prepare($query);
         $sth->execute($eType, $eEncoding);

         SessionHdl_clearVar($dbh,$ssid,"exp_rid");

         $sth->finish;


    }
}


############################################################

if ($input->{'save'}) {
    my $dbName = Opals::Context->config('db_name');
    my $mrcFile = $input->{'save'};
    print $cgi->header(
        -type       => 'text/marc',
        -attachment => $mrcFile,
    );
    open MRC, "</data/opals/export/$dbName/$mrcFile";
    while (<MRC>) {
        print $_;
    }
    close MRC;
    exit;
}
############################################################

my $sth = $dbh->prepare(<<_STH_);
select  *, to_days(dateExpiry) - to_days(now()) as deltaExpiry
from    opl_marcExport
order by dateRequest desc
_STH_

my @request;

my $exportType={date     => "date range",
                rid      => "record id",
                all      => "entire collection",
                modDate_r=> "record modified",
                modDate_h=> "holding modified",
                ridList_r=> "record list",
                ridList_h=> "holding modified of record list"
                };
my ($user, $guardian,$eType);

$sth->execute() || return;
while (my $req = $sth->fetchrow_hashref) {
    ($user, $guardian) = user_getInformationById($dbh, $req->{'uid'});
    $req->{'firstname'} = $user->{'firstname'};
    $req->{'lastname'} = $user->{'lastname'};
    $eType = $req->{'eType'}; 
    if($eType eq "hitlist" || 
        ($eType eq "ridList_r" && $req->{'eFrom'} eq "" && $req->{'eTo'} eq "")){
        $req->{'eType'} = "hitlist";
    }
    else{        
        $req->{'eType'} = $exportType->{$req->{'eType'}};
    }

    $req->{'eFrom'} =~ s/([\d]{4}-[\d]{2}-[\d]{2}) .*/$1/;
    $req->{'eTo'} =~ s/([\d]{4}-[\d]{2}-[\d]{2}) .*/$1/;
    $req->{'dateExpiry'} =~ s/([\d]{4}-[\d]{2}-[\d]{2}) .*/$1/;

    $req->{'status_'.$req->{'status'}} = 1;
    $req->{'isExpired'} = ($req->{'deltaExpiry'} < 0);
        
    if($req->{'eType'} eq "hitlist"){
        $req->{'range'} = ""; #$req->{'ridList'};
    }
    elsif ($req->{'eTo'} eq $req->{'eFrom'}){
        $req->{'range'} =  $req->{'eFrom'};
    }
    else{
        $req->{'range'} =   $req->{'eFrom'} . " - " . $req->{'eTo'};
    }
    #$req->{'fEqualT'} = ($req->{'eTo'} eq $req->{'eFrom'}) ?1 :0;
    
    push @request, $req;
}
$sth->finish;
$template->param(
    load_export => 1,
#    jsCheckSkip => (($eFrom || $eTo) && $ENV{'REQUEST_METHOD'} =~ m/get/i),
#    eFrom       => $eFrom,
#    eTo       => $eTo, 
     request     => \@request,
#    dbName      => Opals::Context->config('db_name'),
);
#Mon, Jan 11, 2010 @ 15:13:16 EST

my($minAR_readingLevel,$maxAR_readingLevel)=slr_getARLMinMax_fieldVal('accelerated reader','AR_readingLevel');
my($minRC_readingLevel,$maxRC_readingLevel)=slr_getARLMinMax_fieldVal('reading counts','RC_readingLevel');

my($minAR_pointValue,$maxAR_pointValue)=slr_getARLMinMax_fieldVal('accelerated reader','AR_pointValue');
my($minRC_pointValue,$maxRC_pointValue)=slr_getARLMinMax_fieldVal('reading counts','RC_pointValue');

my($min_lexileValue,$max_lexileValue)=slr_getLexileMinMax();
$template->param(
    minAR_readingLevel  =>$minAR_readingLevel,
    maxAR_readingLevel  =>$maxAR_readingLevel,
    minRC_readingLevel  =>$minRC_readingLevel,
    maxRC_readingLevel  =>$maxRC_readingLevel,
    minAR_pointValue    =>$minAR_pointValue,
    maxAR_pointValue    =>$maxAR_pointValue,
    minRC_pointValue    =>$minRC_pointValue,
    maxRC_pointValue    =>$maxRC_pointValue,

    min_lexileValue     =>$min_lexileValue,
    max_lexileValue     =>$max_lexileValue,
);


my $msgValMap ={};
my $stdMsgMap            =loc_getMsgFile('item/export.msg',$msgValMap);
my $arlMsgMap            =loc_getMsgFile('search/arl.msg');
loc_write($template,$stdMsgMap);
loc_write($template,$arlMsgMap);


tmpl_write($dbh, $cgi, $cookie, $template);
################################################################################


sub isExporting {
    my ($dbh) = @_;

    my ($eCount) = $dbh->selectrow_array(<<_SQL_);
select  count(*)
from    opl_marcExport
where   status in ('waiting', 'processing')
_SQL_

    return $eCount;
}
