#!/usr/bin/perl 

use lib "/www/opals/module";;
use Opals::Context('/etc/opals/conf/alp_alp');

use strict;
use Opals::UrlRegistry qw(
    ureg_getUrlRegistry
    ureg_getMenu
);
use Time::HiRes qw( time );
use CGI;
use DBI;
use Text::CSV_XS;
use Opals::Circulation qw(
    circ_getItemInfo
);
use Opals::Date qw(
    date_parse
    date_deltaWorkDayHour
    dateTime_parse
);
use POSIX qw(
    ceil
    floor
);
use Digest::SHA qw(
    sha1_base64
);
use MARC::File::USMARC;
use MARC::File::XML;


use Opals::Transaction qw(
    trans_chargeOverdue
    trans_chargeLost
);
use JSON;
my $dbh = Opals::Context->dbh();
my $dbh = Opals::Context->dbh();
my $zRoot   = Opals::Context->config('zRoot');
my $zPort   = Opals::Context->config('zPort');
my $zDatabase = Opals::Context->config('zDatabase');
=item 
The file structure is

001     M3 transaction database key (10 digits)

010#d   Transaction creation date and time

010#g    Transaction due date and time

010#e    Transaction close date and time

010#m    ISN (m3 database key) of patron borrowing item

852#p    Barcode number of patron

010#l    ISN (m3 database key) of holding loaned

852#p    Barcode number of item loaned
=cut


my $csv = Text::CSV_XS->new({ binary => 1 });
my $transFile =@ARGV[0];
if(!defined $transFile || !-f $transFile){
    print  "ERROR: Missing trans file\n";
    exit 0;
}
$dbh->do("DROP TABLE IF EXISTS `opl_loan_past`");
$dbh->do("CREATE TABLE opl_loan_past like opl_loan");
open ERR ,">/tmp/m3TransCnvErr.csv";
my @trans=readTransFile($transFile);
shift @trans;
shift @trans;
foreach my $t(@trans){
    $csv->parse($t);
    my @fields = $csv->fields();
    convert_loan_trans($dbh,\@fields);

    #last if($count++>10);
}
my ($maxIdloan)=$dbh->selectrow_array("select max(idloan) from opl_loan_past");
$dbh->do("update opl_loan set idloan=idloan+$maxIdloan");
$dbh->do("update opl_odl set idloan=idloan+$maxIdloan");
$dbh->do("insert into opl_loan select * from opl_loan_past");
updateUserLoanStats($dbh);
close ERR;
#field index 1:dateLoan;2:dateDue;3:dateReeturn;5:userbarcode;7:item parcode



############################################################
sub convert_loan_trans{
    my($dbh,$fields)=@_;
    my $fieldMap={
    itemBc=>7,
    userBc=>5,
    dateLoan=>1,
    dateDue=>2,
    dateReturn=>3
    };

    if(scalar(@$fields)>=6){
        my $userbarcode=@$fields[5];
        my $barcode=@$fields[7];
        my $dateLoan=parseDateTime(@$fields[1]);
        my $dateDue=parseDateTime(@$fields[2]);
        my $dateReturn=parseDateTime(@$fields[3]);
        $dateDue=~ s/22:00:00$/23:59:59/g;
        my($uid)=$dbh->selectrow_array("select uid from opl_user where userbarcode=?",undef,$userbarcode);
        my($rid)=$dbh->selectrow_array("select rid from opl_item where barcode=?",undef,$barcode);
        if($rid){
            $uid=0 if(!defined $uid);
            my ($idloan,$dateRenewal)=$dbh->selectrow_array("select idloan,dateReturn from opl_loan_past where barcode=? && dateLoan=? && uid=?",undef,$barcode,$dateLoan,$uid);
            if($idloan){
                $dbh->do("update opl_loan_past set dateDue=?,dateReturn=?,dateRenewal=? where idloan=?",undef,$dateDue,$dateReturn,$dateRenewal ,$idloan);
            }
            else{
                $dbh->do("insert into opl_loan_past set uid=?,barcode=?,dateLoan=?,dateDue=?,dateReturn=?",undef,$uid,$barcode,$dateLoan,$dateDue,$dateReturn);
            }
        }
        else{ #report not invalid transactions
            my $n=scalar(@$fields);
            if(!defined $uid){
                @$fields[$n-1]="user barcode does not exist($userbarcode)";
            }
            else{
                @$fields[$n-1]="item barcode does not exist($barcode)";
            }

            print ERR join(",",@$fields),"\n";
            #$err_loan++;
            #print TRANS_ERR_LOAN join(",",@$fields), "\n";
        }
    }
    else{
        print join(@$fields),"\n";
    }

}
############################################################
############################################################
sub parseDateTime{
    my ($dtStr)=@_;
    my $ret="";
    if($dtStr =~ m/^\d{12}/){
       $ret=sprintf "%s-%s-%s %s:%s:%s",substr($dtStr,0,4),substr($dtStr,4,2),substr($dtStr,6,2),substr($dtStr,8,2),substr($dtStr,10,2),substr($dtStr,12,2);
    }
    return $ret;
}
############################################################
sub readTransFile{
    my ($csvFile)=@_;
    my @trans=();
   
    if(-f $csvFile){
        open IN,"<$csvFile";
        while(<IN>){
            chomp;
            push @trans,$_;
        }
    }
    return @trans;

}


############################################################
sub updateUserLoanStats{
    my($dbh) =@_;
    my $sth=$dbh->prepare("select uid,circStats from opl_user");
    
    $sth->execute();
    while(my($uid,$circStats)=$sth->fetchrow_array){
        $circStats="{}" if(!$circStats || $circStats eq '');
        my $circStatsJson=decode_json($circStats);
        $circStatsJson->{'L'}=getUserIdloanList($dbh,$uid);
        $dbh->do("update opl_user set circStats=? where uid=?",undef,to_json($circStatsJson),$uid);
    }
}
############################################################
sub getUserIdloanList{
    my($dbh,$uid) =@_;
    my $sth=$dbh->prepare("select idloan from opl_loan where uid = ?");
    $sth->execute($uid);
    my $idloanList=[];
    while(my($idloan)=$sth->fetchrow_array){
        push @$idloanList,$idloan;
    }
    return $idloanList;
}

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


sub loadConfig {
    my ($configFile) = @_;
#    print "Enter the config filename of Opals: ";
#    $configFile = <STDIN>;
    my $config = {};

    open CONF, $configFile || die "Cannot open file $configFile";
    while (<CONF>) {
        chomp;
        s/#.*//;                # remove comments
        next if /^\s*$/;        # ignore blank lines

        if (/^\s*(\w+)\s*=\s*(.*?)\s*$/) {
            $config->{$1} = $2;
        }
    }
    close CONF;

    return $config;
} 

exit 0;
  
