#!/usr/bin/perl

#use utf8;
use strict;
use CGI;

use Opals::Context;
use Opals::Template qw(
    tmpl_read
    tmpl_write
);
use Textbook::Record qw(
    tbkrec_rectify
);

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

my $cgi = CGI->new;
# $cgi->param('aaa') returns an array of aaa
my $input = $cgi->Vars();
#my $op = $input->{'op'};
my ($permission, $cookieList, $template) = tmpl_read(
    {
        dbh             => $dbh,
        cgi             => $cgi,
        tmplFile        => 'textbook/imrec.tmpl',
        reqPermission   => '',
#        op              => $op,
    }
);

# See User.pm for the list of permissions
#if ($permission && $permission->{'reqPermission1'}) {

    

#}
#else { # input for login form
#    my @form_input;
#    foreach my $param (keys %{$input}) {
#        push @form_input, {name =>"$param",value => "$input->{$param}"};
#    }
#    $template->param(
#        input=>\@form_input,
#    );
#}

# Turn on/off search box
#$template->param(
#    search_off      => 1,
#);

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


sub importFile {
    my ($dbh, $params) = @_;

    my $data = $params->{'data'};
    my $enc  = $params->{'enc'};

    my @rec = split(/\x1D/, $data);
    $data = '';
    foreach my $r (@rec) {
        $data .= "$r\x1D" if (length($r) > 24);
    }

    my $msgDigest = sha512_hex($data);

    @rec = split(/\x1D/, $data);

    my ($sth, $col) = tbkrec_importRecordSth($dbh);

    foreach my $r (@rec) {
        my $marc = MARC::File::USMARC->decode($r);#, \&mc21_filter);

        $marc = tbkrec_rectify($marc);
        next unless $marc->fields();

        tbkrec_importRecord($marc, $sth, $col);
    }

}
