#!/usr/bin/perl

#use utf8;
use strict;
use CGI;
use MARC::File::USMARC;
use POSIX qw(
    ceil
);

use Opals::Context;
use Opals::Template qw(
    tmpl_read
    tmpl_write
    tmpl_rangedPageList
);

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        => 'marc21/list.tmpl',
        }
);

#my $zid = $input->{'zid'};
#($zid && $zid >= 0) || ($zid = 0);
#
my $type = $input->{'type'};
my $iid = $input->{'iid'};
my $total = $input->{'total'};
my $pNum = $input->{'pNum'};
my $pSize = $input->{'pSize'};

($type =~ m/(import|veto)/) || ($iid = 0);
$iid = validateNumber($iid);
$total = validateNumber($total);
$pNum = validateNumber($pNum);
$pSize = validateNumber($pSize);

($pSize && $pSize > 0) || ($pSize = 10);
($pNum > 0) || ($pNum = 1);
($pNum <= ceil($total/$pSize)) || ($pNum = ceil($total/$pSize));

if ($iid) {
    my @rec;
    my $imex = Opals::Context->config('imex');
    my $db_name = Opals::Context->config('db_name');

    my $src = "$imex/import/$db_name/$iid";

    if ($type ne 'import') {
        $src .= ".$type";
    }

    if (-r $src) {
        my $marcfile = MARC::File::USMARC->in( "$src" );

        my $offset = ($pNum - 1) * $pSize;
        my $pLimit = $offset + $pSize;
        my @listingInfo;
        for (my $i = 0; ($i < $pLimit) && ($i < $total); $i++) {
            if ($i < $offset) {
                $marcfile->skip();
                next;
            }
            my $rec = $marcfile->next() || last;
            my $li = getListingInfo($rec);
            $li->{'order'} = $i + 1;
            push @listingInfo, $li;
        }

        $marcfile->close();

        my $pRange = 10;
        my @rangedPageList = 
            tmpl_rangedPageList($total, $pNum, $pSize, $pRange);
        $template->param(
            fileType => ($type eq 'import') ? 'Uploaded' : 'Vetoed',
            type => $type,
            iid => $iid,
            total => $total,
            pNum => $pNum,
            pSize => $pSize,
            rec_start => $offset + 1,
            rec_end => ($offset + scalar(@listingInfo)),
            rangedPageList => \@rangedPageList,
            listingInfo => \@listingInfo,
        );
    }

    $template->param(
        rec => \@rec,
    );
}
else {
    $template->param(
        error => 1,
    );
}

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


sub validateNumber {
    my ($num) = @_;

    if (!$num || $num =~ m/\D/) {
        $num = 0;
    }

    return $num;
}
##############################


sub getListingInfo {
    my ($rec) = @_;

    my $title = $rec->subfield('245', 'a');
    my $author = $rec->subfield('100', 'a');
    my $pubDate = $rec->subfield('260', 'c');
    my @holdings;
    foreach my $f852 ($rec->field('852')) {
        push @holdings, {
                callNumber => getCallNumber($f852),
                barcode => $f852->subfield('p'),
            };
    }

    return {
        title => $title,
        author => $author,
        pubDate => $pubDate,
        holdings => \@holdings,
        cHolding => scalar(@holdings),
    };
}
##############################


# function copied from Marc21.pm
sub getCallNumber {
    my ($holding) = @_;
    
    my $callNumber = 
            $holding->subfield('k') . ' ' .
            $holding->subfield('h') . ' ' .
            $holding->subfield('i') . ' ' .
            $holding->subfield('m');
    $callNumber =~ s/ +/ /g;
    $callNumber =~ s/(^ | $)//g;

    ($callNumber) || ($callNumber = '');

    return $callNumber;
}
