#!/usr/bin/perl

#use utf8;
use strict;
use CGI;
use Text::CSV_XS;
use Digest::SHA qw(
    sha1_base64
    sha1_hex
);

use Opals::Context;
use Opals::Template_ajax qw(
    tmpl_read
    tmpl_write
);

use Opals::Date qw(
    date_f005
);

use MARC::Record;
use MARC::Field;
use MARC::File::XML;
use MARC::File::USMARC;

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

my $cgi          = CGI->new;
my $input        = $cgi->Vars();

my $fname = $input->{'file'};
my $fdata = $cgi->param('file');
my ($permission, $cookie, $template) = tmpl_read(
        {
            dbh             => $dbh,
            cgi             => $cgi,
            tmplFile        => 'ajax/util/uploadMarc.tmpl',
        }
    );
    
    my $upload_filehandle = $cgi->upload("file"); 
    my $marcStr="";
    while ( <$upload_filehandle> ){
        $marcStr .= $_;
    }
    my $marc = MARC::File::USMARC->decode($marcStr);
    my $status=validateMarc($marc);
    $template->param(status => $status );
    if($status){
        my @fields = $marc->field('001');
        $marc->delete_fields(@fields);
        @fields = $marc->field('852');
        $marc->delete_fields(@fields);
        my $f001 = MARC::Field->new( '001', '');
        $marc->insert_fields_ordered(($f001));
        
        my $marcXml = MARC::File::XML::record($marc);
        umask 002;
        my $tmpFile=`/bin/mktemp`;
        $tmpFile =~ s/\n$//gi;
        system("chown apache.apache $tmpFile");
        system("chmod 664 $tmpFile");
        open    MARCXML, ">$tmpFile" ;
        binmode MARCXML;
        print MARCXML $marcXml;
        close MARCXML;
        $template->param(filePath =>$tmpFile );
    }

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

#------------------------------------------------------------------------------

sub validateMarc{
    my($marc)=@_;

    if ($marc->leader) {
        my $leader = $marc->leader;
        my $title =$marc->subfield( '245', 'a');
        $leader =~ s/\s//g;
        return 0 if($leader eq'' || !defined $title);
     }
    return 1;

}
#------------------------------------------------------------------------------
