#!/usr/bin/perl

use strict;
use CGI;
use Time::localtime;
use JSON;

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

use Opals::Mail qw(
    mail_send
);

use Opals::Eq_Search qw(
      
    eq_category_getList
    eq_category_getListById
    eq_search_cat
    eq_search_countByCat

);

use Opals::Eq_SolrSearch;

use Opals::Equipment qw(

    eq_record_findByRId

);

use Opals::Eq_Circulation qw(

    circ_infoRecord
    circ_getLoanListByRid
    circ_getItemStatus

);
use Opals::Equipment qw(

    eq_defItem_getList
    eq_defRecord_getList
    eq_categoryMapList

);


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

my $cgi = CGI->new;
my $input = $cgi->Vars();
my ($permission, $cookieList, $template) = tmpl_read(
    {
        dbh             => $dbh,
        cgi             => $cgi,
        tmplFile        => 'eqmnt/util/save_sendRec.tmpl',
        reqPermission   => 'eq_record_edit',
    }
);


my $tm = localtime;
my $curTime = sprintf("%04d%02d%02d%02d%02d%02d", $tm->year+1900, ($tm->mon)+1, $tm->mday, $tm->hour, $tm->min, $tm->sec);
my $today = sprintf("%04d-%02d-%02d %02d:%02d:%02d", $tm->year+1900, ($tm->mon)+1, $tm->mday, $tm->hour, $tm->min, $tm->sec);
   my $rid = $input->{'rids'};
   my $op  = $input->{'op'};
   my $type = $input->{'type'};
   my @rids = split(/,/,$rid);
   my @list=();
   my @selFields = ($cgi->param('selFields'));

   my $defRecList = eq_defRecord_getList($dbh);
   my $defItmList = eq_defItem_getList($dbh);
   my $circStatus = $input->{'circStatus'};
   my $mapDefField = {};
   foreach my $d (@{$defRecList}, @{$defItmList}){
       $mapDefField->{$d->{'id'}} = $d->{'name'};
   }
   $mapDefField->{'bldName'}    = "Building Name";
   $mapDefField->{'bldAddress'} = "Building Address";
   $mapDefField->{'bldCity'}    = "Building City";
   $mapDefField->{'bldState'}   = "Building State";

if ($op eq 'save'){
    my $content ="";
    my @recList = ();
    foreach my $id  (@rids){
        my $recInfo =  eq_record_findByRId($dbh, {recordId=>$id});
        push @recList,{
            rid     =>  $id,
            name    =>  $recInfo->[0]->{'rname'},
            rInfo   =>  $recInfo
        }
    }
    my $list = getList($dbh,$today,\@recList);
    print "Content-Type:application/x-download\n";
    print "Content-Disposition:attachment;filename=eqmntRecords.html\n\n";     
    print $list;
}
elsif ($op eq 'listEditorSave'){
    my $filename = "eqmntFromListEditor_$curTime";
    my $ridList = $input->{'ridList'};
    my @selFields = ($cgi->param('selFields'));

    my $categoryList = eq_categoryMapList($dbh);

    my $eq_solrSearch = Opals::Eq_SolrSearch->new(dbh=>$dbh);
    my $lQuery = $eq_solrSearch->eq_slr_buildQuery_recordList_json($input);
    
    my($sHost,$sPort,$sDatabase) = $eq_solrSearch->eq_getSolrSrvInfo();
    my $url="http://$sHost:$sPort/solr/$sDatabase/select?$lQuery";

    my $timeout = 600;
    my $userAgent = LWP::UserAgent->new(agent   => 'OPALS', timeout=>$timeout);
    my $request = HTTP::Request->new(GET => $url); 
    my $response = $userAgent->request($request );

    my $json = $response->content;

    my $rs = from_json($json);
    my $result = $rs->{'response'};
    my $hits = $result->{'numFound'};
    my $recList = $result->{'docs'};
    foreach my $r (@{$recList}){
        foreach my $c(@{$r->{'category_facet'}}){
            if ($r->{'category'} && $r->{'category'} ne ""){
                $r->{'category'} .= ","
            }
            $r->{'category'} .= $categoryList->{$c};
            my $itm = circ_getItemStatus($dbh,{barcode=>$r->{'eq_barcode'}});
            $r->{'itemStatus'} = getStyleByStatus($itm->{'status'});
            $r->{'itemStatusDetail'} = $itm;

        }
    }
    if ($type eq 'HTML') {
        print "Content-Type:application/x-download\n";
        print "Content-Disposition:attachment;filename=$filename".".html\n\n";  
        print "<html> <head>";
        print "<style type='text/css'>";
        print "table.reportTbl{border-collapse:separate;border-spacing:0;empty-cells:show} ";
        print "table.reportTbl th,td {font-size:12px;}";
        print "table.reportTbl thead {  background: #C0C0C0;  color: #fff;}";
        print "table.reportTbl th {  font-weight: bold;  text-align:center;  border:none;}";
        print "table.reportTbl tbody tr:nth-child(even) {  background: #f0f0f2;}";
        print "table.reportTbl td {border-bottom: 1px solid #F0F0F0; border-right: 1px solid #F0F0F0;}";
        print " table.reportTbl td:first-child {  border-left: 1px solid #F0F0F0;}";
        print "</style>";
        print "<body>";
        print "<div style='margin-left:auto;margin-right:auto;text-align:center;font-size:12px;'>";
        ($hits>1)?print "<p>There are $hits items.</p>":print "<p>There is $hits item.</p>";
        print "</div>";
        print "<table class='reportTbl'>";
        print "<thead>";
        print "<tr><th>No.</th><th>Equipment Name</th><th>Barcode</th><th>Category</th><th>Item Type</th>";
        foreach my $selField (@selFields){
            print "<th>  $mapDefField->{$selField} </th>";
        }
        if ($circStatus){
            print "<th>  Circ. Status </th>";
            print "<th>  Borrower </th>";
            print "<th>  Due Date </th>";
        }
        print "</tr>";
        print "</thead>";
        print "<tbody>";
        my $i =0;
        foreach my $r (@{$recList}) {
            $i++;
            print "<tr>";
            print "<td>$i</td><td>$r->{'eq_name'}</td><td>$r->{'eq_barcode'}</td><td>$r->{'category'}</td><td>$r->{'typeId'}</td>";
            foreach my $selField (@selFields){
                print "<td> $r->{$selField} </td>";
            }
            if ($circStatus){
                print "<td> $r->{'itemStatus'}  </td>";
                if ($r->{'itemStatus'} eq "on loan"){
                    print "<td>  $r->{'itemStatusDetail'}->{'patron_name'} </td>";
                    print "<td> $r->{'itemStatusDetail'}->{'l_duedate'} </td>";
                }
                else{
                    print "<td></td><td></td>"
                }
            }
            print "</tr>";
        }
        print "</tbody>";
        print "</table>";
        print "</body></head></html>";
    }
    elsif($type eq 'CSV'){
        print "Content-Encoding: UTF-8\n";
        print "Content-type: text/csv; charset=UTF-8\n";
        print "Content-Disposition:attachment;filename=$filename".".csv\n\n"; 
        print "\"Equipment Name\",\"Barcode\",\"Category\",\"Item Type\" ";
        foreach my $selField (@selFields){
            print ",\"$mapDefField->{$selField}\"";
        }
        if ($circStatus){
            print ",\"Circ. Status\"";
            print ",\"Borrower\"";
            print ",\"Due Date\"";
        }
        print "\n";
        foreach my $r (@{$recList}) {
            while (my ($k,$v)= each %{$r}){
                $r->{$k} =~ s/"/""/g;
            }
            print "\"$r->{'eq_name'}\",\"$r->{'eq_barcode'}\",\"$r->{'category'}\",\"$r->{'typeId'}\"  ";
            foreach my $selField (@selFields){
                print ",\"$r->{$selField}\"";
            }
            if ($circStatus){
                print ",\" $r->{'itemStatus'}  \"";
                if ($r->{'itemStatus'} eq "on loan"){
                    print ",\" $r->{'itemStatusDetail'}->{'patron_name'} \"";
                    print ",\" $r->{'itemStatusDetail'}->{'l_duedate'} \"";
                }
                else{
                    print ", , "
                }
            }
            print "\n";
        }
    }

}
else{
    tmpl_write($dbh, $cgi, $cookieList, $template);
}

sub getList {

    my($dbh,$date,$list) = @_;
    my $rootDir   = Opals::Context->config('rootDir');

    my $template = HTML::Template->new(    
        filename            => "save_sendRec.tmpl",
        path                => "$rootDir/htdocs/theme/opals/eqmnt/util/",
        global_vars         => 1,
        die_on_bad_params   => 0,
        cache               => 1,
        shared_cache        => 0,
        loop_context_vars   => 1,);

    $template->param(
        list=>$list,
        date=>$date,
        );
    return  $template->output();

}

sub getStyleByStatus {
     
    my ($statusCode) = @_;

    my ($itemStatus) = ('available');
    if($statusCode == 2){
        ($itemStatus) = ('reserved');
    }
    elsif($statusCode == 3){
        ($itemStatus) = ('on loan');
    }
    elsif($statusCode == 4){
        ($itemStatus) = ('overdue');
    }
    elsif($statusCode == 5){
        ($itemStatus) = ('on hold');
    }
    elsif($statusCode == 7){
        ($itemStatus) = ('lost');
    }
    elsif($statusCode == 8){
        ($itemStatus) = ('damage');
    }
    elsif($statusCode == 10){
        ($itemStatus) = ('restricted');
    }
    elsif($statusCode == 11){
        ($itemStatus) = ('missing');
    }
   
   return ($itemStatus) ;
}

