#!/usr/bin/perl

#use utf8;
use strict;
use CGI;

use Opals::Context;use Digest::SHA qw(
    sha512_hex
);
use Date::Calc qw(Today Add_Delta_Days Day_of_Week Week_Number Day_of_Year);
use Time::localtime;
use MARC::Field;
use MARC::File::USMARC;

use Opals::Search qw(
 
    srch_F852Default_marc21

);


use Opals::Template qw(
    tmpl_read
    tmpl_write
    tmpl_preference
);

use Opals::Tb_Record qw(
    
    tb_itemType_getList

);

use Opals::Tb_Import qw(
    tb_m21_import
    tb_m21_getFileName
);


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        => '/txtbk/record/import.tmpl',
            reqPermission   => 'tb_record_edit',
        }
);

#get default system-library codes

my $default852 = srch_F852Default_marc21($dbh);
my $sCode =  $default852->subfield('a');
my $lCode =  $default852->subfield('b');


my $tm = localtime;
my $dateToday = sprintf("%04d-%02d-%02d %02d:%02d:%02d", $tm->year+1900, ($tm->mon)+1, $tm->mday, $tm->hour, $tm->min, $tm->sec);
my $sth;
my ($mesgDigest, $iid, $fileDuplicated);

my $syspref = tmpl_preference($dbh);
my $autoAdd2NewItemList = $syspref->{'autoAdd2NewItemList'};

$autoAdd2NewItemList=0 if ($autoAdd2NewItemList !~ m/^0$|^1$/);
    my($year,$month,$day)=Today();
    ($year,$month,$day) = Add_Delta_Days($year,$month,$day,90);
    my $defaultNewItemExpDate=sprintf("%04d-%02d-%02d",$year,$month,$day);
    my $newItemExpDate; 
    $newItemExpDate = $defaultNewItemExpDate if ( !$newItemExpDate);
my $marc = $cgi->param('marc');
my $op = $input->{'op'};

my $selItemType = $input->{'itemType'};
    ($selItemType || $selItemType eq "");

if ($marc && $ENV{'REQUEST_METHOD'} =~ m/post/i && $op eq 'load') {
    my $uid = $template->param('curUserId');
    my $encoding  = $input->{'encoding'};
    ($encoding eq 'MARC-8') || ($encoding = 'UTF-8');
    my $addToNewItemList = $input->{'addToNewItemList'};
    $addToNewItemList =0 if(!$addToNewItemList || $addToNewItemList !=1);
    $newItemExpDate = $input->{'newItemExpDate'};
      
    my $marcFile = '';
    while (<$marc>) {
        $marcFile .= $_;
    }
    my @mRec = split(/\x1D/, $marcFile);
    $marcFile = '';
    foreach my $rec (@mRec) {
        $marcFile .= "$rec\x1D" if (length($rec) > 24);
    }
    $mesgDigest = sha512_hex($marcFile);
    @mRec = split(/\x1D/, $marcFile);
    my $countTotal = $#mRec + 1;
    my $db_name = Opals::Context->config('db_name');
    my $imex    = Opals::Context->config('imex');
    $sth = $dbh->prepare(<<_STH_);
insert into tb_marcImport
set 
    uid         = $uid,
    sCode       = ?,
    lCode       = ?,
    itemType    = ?,
    encoding    = ?,
    countTotal  = $countTotal,
    dateUpload  = now(),
    mesgDigest  = ?
_STH_
    $sth->execute($sCode,$lCode,$selItemType,$encoding, $mesgDigest);
    $sth->finish();
 # uploads with invalid status are ignored.
    $sth = $dbh->prepare(<<_STH_);
select  iid
from    tb_marcImport
where   mesgDigest = ? &&
        status = 'uploaded'
order by dateUpload desc
limit 1
_STH_
    $sth->execute($mesgDigest);
    ($iid) = $sth->fetchrow_array;
    my $file = tb_m21_getFileName($iid);
    open FILEIMPORT, ">$file";
    print FILEIMPORT $marcFile;
    close FILEIMPORT;
 # Check if file has been uploaded
    $sth = $dbh->prepare(<<_STH_);
select  count(*)
from    tb_marcImport
where   mesgDigest = ? &&
        status in ('accepted','done')
_STH_
    $sth->execute($mesgDigest);
    ($fileDuplicated) = $sth->fetchrow_array;
    $sth->finish();
    if ($fileDuplicated) {
        $template->param(
            fileDuplicated  => 1,
            iid             => $iid,
        );
    }
    else {
        $template->param(
            fileUploaded => validateUpload($dbh, $iid),
        );
    }
}
if ($input->{'iid'} && $ENV{'REQUEST_METHOD'} =~ m/post/i && !$op) {
    if ($input->{'imDup'} == 1) {
        $template->param(
            fileUploaded => validateUpload($dbh, $input->{'iid'}),
        );
    }
    else {
        $template->param(
            fileDeleted => deleteUpload($dbh, $input->{'iid'}),
        );
    }
}

if ($op && $op eq 'import' && $input->{'iid'} ){
    
    tb_m21_import($dbh, $input->{'iid'} );

}

my $tbItemTypeList    = tb_itemType_getList($dbh);
$template->param(
    tbItemTypeList  =>    $tbItemTypeList
);

$template->param(
    sCode       => $sCode,
    lCode       => $lCode,
    selItemType => $selItemType,
);


my $catType = Opals::Context->config('type');
my @importInfo;

$sth = $dbh->prepare(<<_STH_);
select  m.*, 
        u.uid, u.firstname, u.lastname, 
        (countTotal - countProcessed) as countImporting
from    tb_marcImport as m left outer join opl_user as u on m.uid = u.uid
where   m.status in ('accepted','done')
order by iid desc
_STH_

$sth->execute();
my $sth_mergeCount = $dbh->prepare(<<_STH_);
select  count(*)
from    tb_marcDuplicate
where   iid = ?
_STH_

while(my $iInfo = $sth->fetchrow_hashref){

    $sth_mergeCount->execute($iInfo->{'iid'});
    ($iInfo->{'countPending'}) = $sth_mergeCount->fetchrow_array;
    if ($iInfo->{'countTotal'} == $iInfo->{'countProcessed'}) {
        $iInfo->{'countIgnored'} =
            $iInfo->{'countTotal'}
          - $iInfo->{'countImported'}
          - $iInfo->{'countMerged'}
          - $iInfo->{'countPending'};
    }
    else {
        $iInfo->{'countIgnored'} = 0;
    }


    $iInfo->{'recInStatus_'.$iInfo->{'status'}} = 1;
    
    push @importInfo, $iInfo;
}
$sth->finish;


$template->param(
   importInfo => \@importInfo,  
);

tmpl_write($dbh, $cgi, $cookie, $template);
#$dbh->disconnect();
################################################################################

sub validateUpload {
    my ($dbh, $iid) = @_;

    my $rv = $dbh->do(<<_STH_);
update  tb_marcImport
set     status = 'accepted',
        dateUpload = now()
where   iid = $iid
_STH_

    return $rv;
}
sub deleteUpload {
    my ($dbh, $iid) = @_;

    my $rv = $dbh->do(<<_STH_);
delete from tb_marcImport
where   iid = $iid
_STH_

    my $db_name = Opals::Context->config('db_name');
    my $imex    = Opals::Context->config('imex');
    unlink getFileName($iid);

    return $rv;
}

sub getFileName {
    my ($iid) = @_;
    my $db_name = Opals::Context->config('db_name');
    my $imex    = Opals::Context->config('imex');
    return  "$imex/import/$db_name/tb.$iid";

}

