#!/usr/bin/perl -w

#SITE=ztest; INFILE=/tmp/textbook.mrc; \cp -fp script/util/tbk_marc_import /tmp/ttt; perl -pi -e "s/_SITECODE_/$SITE/" /tmp/ttt; /tmp/ttt $INFILE
#
#SITE=ztest
#INFILE=/tmp/textbook.mrc
#\cp -fp script/util/tbk_marc_import /tmp/ttt
#perl -pi -e "s/_SITECODE_/$SITE/" /tmp/ttt
#/tmp/ttt $INFILE

use lib "/www/opals/module";
use Opals::Context("/etc/opals/conf/ztest");
use Time::localtime;

use strict;
use Opals::Equipment qw(
    eq_def_getList_brief

);

use MARC::Field;
use MARC::File::USMARC;


my $dbh = Opals::Context->dbh();;
END {
    if ($dbh) {
        $dbh->disconnect();
    }
}


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);

$| = 1;
# Codes start...
my $mapRecord = {

    '0eqName'  => {
                    245 => {a => 1 }, 
               },
    1       => {
                    100 => {a => 1},
                },
    3       => {    245 => { b=>1},
            },
    36      => {
                    300 => {
                            3 => 1,
                            6 => 2,
                            8 => 3,
                            a => 4, 
                            b => 5,
                            c => 6,
                            e => 7,
                            f => 8,
                            g => 9
                            },
        },
};

my $mapItem = {
    '0barcode'  => { barcode => {p=>1}},
    '0itemType' => { itemType => {'itemType' => 'EQMT'}},
    6           => { 852 => {9 => 1,}},
    11          => { 852 => {c => 1,}},
    '852a'      => { 852=> {a => 1,}},
    '852b'      => { 852=> {b => 1,}},
    '852d'      => { 852=> {d => 1,}},
    '852e'      => { 852=> {e => 1,}},
    '852f'      => { 852=> {f => 1,}},
    '852h'      => { 852=> {h => 1,}},
    '852i'      => { 852=> {i => 1,}},
    '852k'      => { 852=> {k => 1,}},
    '852v'      => { 852=> {v => 1,}},
    '852x'      => { 852=> {x => 1,}},
    '852z'      => { 852=> {z => 1,}},



};

my $eqDef = eq_def_getList_brief($dbh);

#print $ARGV[0], "\n";
my $marcfile = MARC::File::USMARC->in($ARGV[0]);
my ($r,$i) =(0,0);
my $max = 3;
my $headline;
foreach my $id (sort keys %{$mapRecord}){

    if ($id =~ m/eqName/i){
        $headline .=  "Equipemnt Name" ;
    }
    else{
        $headline .=  $eqDef->{$id} ;
    }
    $headline .= ",";
}

foreach my $id (sort keys %{$mapItem}){
    if ($id =~ m/barcode/i ){
        $headline .= "barcode" ;
    }
    elsif ($id =~ m/itemType/i){
        $headline .= "itemType";
    }
    elsif($id =~ m/^852/i){
        $headline .= $id ;
    }
    else{
        $headline .=  $eqDef->{$id} ;
    }
    $headline .= ",";
}

    $headline =~ s/,$//;
print $headline, "\n";
my $rec ;
my $item;
my $recEmpty;
my $data;
my $tmpBC;
my $noBC=0;
my $tmpfd;
#while ((my $record = $marcfile->next()) && ($r < $max)) {
while (my $record = $marcfile->next() ) {
    $r++;
    $recEmpty = '';
    $rec = '';
    foreach my $id (sort keys %{$mapRecord}){
        foreach my $tag ( keys %{$mapRecord->{$id}}){
            $rec .= '"';
            $recEmpty .= ',';
            foreach my $sf (sort {$mapRecord->{$id}{$tag}{$a} <=> $mapRecord->{$id}{$tag}{$b} } keys %{$mapRecord->{$id}{$tag}}){
                $rec .=  $record->subfield($tag,$sf)? $record->subfield($tag,$sf):'';
            }
            $rec .= '"';
            $rec .= ",";
        }
   }
    my $c = 0;
    foreach my $f ($record->field('852')) {
       $tmpBC = ''; 
       $i++;
       if (! $f->subfield('p')){
            $tmpBC = 'BC_' . $r . '_'.$i ;
            $noBC++;
        }
       $c++;
       $item = '';
       foreach my $id (sort keys %{$mapItem}){
            foreach my $tag ( keys %{$mapItem->{$id}}){
                if ($tag =~ m/itemType/){
                    $item .=  '"' . $mapItem->{$id}{$tag}{$tag} . '"';
                }
                elsif ($tag =~ m/barcode/){
                    $item .= '"';
                    $item .= $f->subfield('p')?$f->subfield('p'):$tmpBC ;
                    $item .= '"';
                }
                else{
                    $item .= '"';
                    $tmpfd = '';
                    foreach my $sf (sort {$mapItem->{$id}{$tag}{$a} <=> $mapItem->{$id}{$tag}{$b} } keys %{$mapItem->{$id}{$tag}}){
                        $tmpfd = $f->subfield($sf) ? $f->subfield($sf): '' ;
                        #$tmpfd =~ s/,//;
                        $item .=   $tmpfd?  $tmpfd :'';
                    }
                    $item .= '"';
                }
            }
            $item .=  ",";
       } 
       $data = '';
       if ($c == 1){
            $data =  $rec . $item ;
       }
       else{
            $data =  $recEmpty . $item ;
       }
    $data =~ s/,$//;
    print $data . "\r\n";
    }
}
print "total records " .  $r .  "\t total holdings " .  $i . "No BC : " . $noBC .  "\n";
$marcfile->close();
# Codes end.

exit 0;


=item
#add record 
sub eq_record_add{
   
    my ($dbh, $params) = @_;
    return -1 if ($params->{'rid'} eq '');
    my ($sql, $sth, $id);
    if ($params->{'reqField'}){
         $sql = "insert into eq_records_MHML set rid=?, rname=?"; 
         $sth = $dbh->prepare($sql);
         $sth->execute($params->{'rid'}, $params->{'fValue'});
         $id = $dbh->{'mysql_insertid'};

        }
    else{
        $sql = "insert into eq_recordFields_MHML set rid=?, fId=?, fValue=?";    
        $sth = $dbh->prepare($sql);
        $sth->execute($params->{'rid'}, $params->{'fId'}, $params->{'fValue'});
        $id = $dbh->{'mysql_insertid'};
    }

    $sth->finish;
    return $id;

}
sub eq_item_add{

    my ($dbh,$params) = @_;
    return -1 if ($params->{'iid'} eq '');
    my ($sql, $sth, $id);
    if ($params->{'reqField'}){
        $sql = "insert into eq_items_MHML set iid=?, rid=?, barcode=?, typeId=?, Available=1, createdDate=now()";
        $sth = $dbh->prepare($sql);
        $sth->execute($params->{'iid'}, $params->{'rid'}, $params->{'barcode'}, $params->{'typeId'});
        $id = $dbh->{'mysql_insertid'};
    }
    else{
        $sql = "insert into eq_itemFields_MHML set iid=?, rid=?, sfId=?, sfValue=?";
        $sth = $dbh->prepare($sql);
        $sth->execute($params->{'iid'}, $params->{'rid'}, $params->{'sfId'}, $params->{'sfValue'});
        $id = $dbh->{'mysql_insertid'};
    }
    $sth->finish;
    return $id;
}


sub eq_record_idGen {
    
    my ($dbh) = @_;
    #my ($sec,$min, $hour, $mday, $mon, $year, $wday, $yday, $isdst) = localtime(time);
    #my $checkSum = sha1_base64($sec,$min, $hour, $mday, $mon, $year, $wday, $yday, $isdst);
    my $checkSum = `date +\%Y\%m\%d\%H\%M\%S\%N`;
    chomp $checkSum;

    my $sql = "insert into opl_idGen_MHML set type = 'equipment', checkSum=? ";
    my $sth = $dbh->prepare($sql);
    $sth->execute($checkSum);
    $sql = "select id from opl_idGen_MHML where type = ? and checkSum=? ";
    $sth = $dbh->prepare($sql);
    $sth->execute('equipment',$checkSum);
    my ($id) = $sth->fetchrow_array();
    $sth->finish;
    return $id;
}
=cut
############################################################
