#!/usr/bin/perl
## LAST UPDATE
### Tue, Mar 22, 2011 @ 15:40:21 EDT
#  for i in enceladus narvi  ; do echo $i; scp /www/odev/htdocs/theme/opals/record/searchform.inc $i:/www/odev/htdocs/theme/opals/record/; scp /www/odev/bin/sessionHdl $i:/www/odev/bin/; scp /www/odev/htdocs/js/ajax.js $i:/www/odev/htdocs/js/ ; done
#

#use utf8;
use strict;
use CGI;
use JSON;
use Opals::Context;
use Opals::Constant;
use Opals::Template qw(
    tmpl_read
    tmpl_write
);
use POSIX qw(
    strftime
    ceil
    floor
);

use Opals::User qw(
    user_getInformationById
);
use Opals::Session qw(
    SessionHdl_clearVar
    SessionHdl_get
);
use Opals::Locale qw(
    loc_getMsgFile
    loc_write
);
use Opals::SolrIndex qw(
    slr_buildSearchQuery_ARL
    slr_search
    slr_getSuggestion
    slr_getARLMinMax_fieldVal
    slr_getLexileMinMax
);

use Opals::Template qw(
tmpl_getSearchFieldList
);

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        => 'record/export.tmpl',
            reqPermission   => 'marc_edit|marc_export',
        }
);

my $zid = 0;

#my $exportList=getExportList($dbh);

my $eType         = $input->{'eType'};
my $eEncoding     = $input->{'eEncoding'};
my ($eFrom, $eTo) = ($input->{'eFrom'}, $input->{'eTo'});
my $exclRecFormat ="";

if ($eType !~ m/^hitlist$/i) {
    my @exclRecFormat= $cgi->param('exclRecFormat');
    $exclRecFormat =join(",",@exclRecFormat);
}

my $ridList="";
my $ssid = $cgi->cookie('globalSessionID');
$template->param(hlpUrl     => Opals::Constant->getHlpUrl('export') );

    $template->param(export=>1);

#my $test=_getItemList($dbh);
my $recordTypeListJSON= to_json(_getRecTypeList(),{pretty=>1});
my $itemTypeListJSON  = to_json(_getItemList($dbh), { pretty => 1})  ;
my ($sfList,$inputSearch)=tmpl_getSearchFieldList($dbh);
my $inputSearch_json   =to_json($inputSearch);
$template->param(
    searchFields    =>$inputSearch_json,
    load_export     => 1,
    recordTypeList  =>$recordTypeListJSON,
    itemTypeList    =>$itemTypeListJSON
);


my $msgValMap ={};
my $stdMsgMap            =loc_getMsgFile('item/export.msg',$msgValMap);
my $arlMsgMap            =loc_getMsgFile('search/arl.msg');
loc_write($template,$stdMsgMap);
loc_write($template,$arlMsgMap);


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

############################################################
sub saveExportFile{
    my ($mrcFile)=@_;
    #if ($input->{'save'}) {
    my $dbName = Opals::Context->config('db_name');
   # my $mrcFile = $input->{'save'};
    print $cgi->header(
        -type       => 'text/marc',
        -attachment => $mrcFile,
    );
    open MRC, "</data/opals/export/$dbName/$mrcFile";
    while (<MRC>) {
        print $_;
    }
    close MRC;
    exit;
    #}
}
############################################################
# Thu, Nov 15, 2012 @ 14:43:26 EST
# This function to create Advance search option: material type
#     Fill recrord types into 5 columns ...
#
sub _getRecTypeList{
    my($cols) =@_;
    $cols =($cols||5);
    my  @mediaTypeTbl = ();
    my $recType =RECTYPE_DEF_TBL;
    my $stdMsgMap  =loc_getMsgFile('search/standard.msg');

    while(my ($key, $value) = each(%$recType)){
        next if($key =~  m/^_/) ;
        my $grp=$value->{'group'}->{'order'} . $value->{'group'}->{'subOrder'} ;
        push @mediaTypeTbl,{mType=>$key,grp=>$grp };

    }

    @mediaTypeTbl = sort{ $a->{'grp'} cmp $b->{'grp'}}  @mediaTypeTbl; 
    my $rows= ceil(scalar(@mediaTypeTbl)/$cols);
    my $i=0;
    my $j=0;
    my @arr=();
    foreach my $r( @mediaTypeTbl){
        $i=0 if($i==$rows);
        push @{$arr[$i]->{"item"}} , {mType     =>$r->{'mType'}, 
                                      mTypeLbl  =>$stdMsgMap->{$r->{'mType'}},
                                      mIcon     =>"/theme/opals/image/medium/".$r->{'mType'}.".png"
                                      };
        $i++;
    }
    return \@arr;
}
    
################################################################################
sub _getItemList {
    my ($dbh) = @_;
    # Get list of item types
    my @itemType;
    my $sth = $dbh->prepare(<<_SQL_);
     select t.*,c.description as category 
from opl_itemType t inner join opl_itemCategory c on t.itemCategory=c.id 
_SQL_
    $sth->execute();
    while (my $rec = $sth->fetchrow_hashref) {
        if($rec->{'defaultType'}){
            $rec->{'selected'}=1;
        }
        push @itemType, $rec;
    }
    $sth->finish;

    return \@itemType;

}

################################################################################
sub isExporting_bk {
    my ($dbh) = @_;

    my ($eCount) = $dbh->selectrow_array(<<_SQL_);
select  count(*)
from    opl_marcExport
where   status in ('waiting', 'processing')
_SQL_

    return $eCount;
}
