#!/usr/bin/perl

use strict;
use CGI;

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

use Opals::Equipment qw(

    eq_defItem_getList
    eq_defRecord_getList

    eq_record_findByRId
    eq_record_addUpdate
    eq_record_update_rname
    
    eq_item_findByRId
    eq_item_addUpdateBarCodeItemType
    eq_item_addUpdate

    eq_item_delete
    eq_item_deleteSubFields
    eq_item_deleteBarcode

    eq_authCtrlFields_getList
    eq_containerFields_getList

    eq_isBarcodeExist
    eq_itemType_getList
);

use Opals::Eq_Search qw(
      
    eq_category_getList
    eq_category_getListById

);

use Opals::Eq_Circulation qw(

    circ_getLoanListByRid

);

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/record/edit.tmpl',
        reqPermission   => 'eq_record_edit',
    }
);


my $rid     = $input->{'rId'};
my $edit    = $input->{'edit'};
my $op      = $input->{'op'};
    $op = "edit" if (!$op ||$op eq "");
my $kw       = $input->{'kw'};
my $sfield   = $input->{'sfield'};
my $sortOrder= $input->{'sortOrder'};
my $sortAttr = $input->{'sortAttr'};
my $pNum     = $input->{'pNum'};

my $recRsPos     = $input->{'recRsPos'};

my $recordInfo = [];
my $itemList;
open debug, ">/tmp/debugK";
while (my ($k,$v) = each (%{$input})){
    print debug "$k=>$v"  , "\n";
}
close debug;
my ($rFieldList,$iFieldList);
my $iDefList        = eq_defItem_getList($dbh);
my $rDefList        = eq_defRecord_getList($dbh);
my $eqItemTypeList  = eq_itemType_getList($dbh);
my $categoryList    = eq_category_getList($dbh);
my $authCtrlFields  = eq_authCtrlFields_getList($dbh);
my $containerFields = eq_containerFields_getList($dbh);

my $libCode         = $template->param('libcode');

my $list = getShowFieldList($dbh,"full");
print debug "list : @{$list}";
foreach my $l (@{$list}){
    print debug " $l \n";
    while (my ($k,$v) = each (%{$l}) ){
        print debug "$k=>$v \n";
    }
}


    foreach my $f (@$rDefList){
        push @$rFieldList , {
           fId      => $f->{'id'},
           fVal     => "",
           fName    => $f->{'name'},
           fDisplay => $f->{'display'},
           fType    => $f->{'fieldType'},
           maxVal   => $f->{'maxVal'},
        }
    }
    foreach my $f(@$iDefList){
        push @$iFieldList, {
             sfId       => ($f->{'sfId'})? $f->{sfId}:$f->{'id'},
             sfVal      => ($f->{'name'} =~ m/Building Code/i)?$libCode: "" ,
             sfName     => $f->{'name'},
             sfReqD     => $f->{'reqD'},
             sfDisplay  => $f->{'display'},
             url_link   => ($f->{'fieldType'} eq '2')?1:0,
             sfType     => $f->{'fieldType'},
             dateType   => ($f->{'dataType'} eq "Date")?"1":"0",
             selectType => ($f->{'dataType'} eq "Select")?"1":"0",
             numberList => ($f->{'dataType'} eq "NumberList")?"1":"0",
             checkboxList=> ($f->{'dataType'} eq "CheckboxList")?"1":"0",
             maxVal     => $f->{'maxVal'},
        }
    }
    $template->param(
        iFieldList      => $iFieldList,
        rFieldList      => $rFieldList,
        eqItemTypeList  => $eqItemTypeList,
        categories      => $categoryList,
        authCtrlFields  => $authCtrlFields,
        containerFields => $containerFields
    );
    $template->param(
         kw             =>  $kw,
         sfield         =>  $sfield,
         sortOrder      =>  $sortOrder,
         sortAttr       =>  $sortAttr,
         pNum           =>  $pNum,
         rid            =>  $rid,
         recRsPos       =>  $recRsPos,
     );

    if ($rid && $rid > 0){
        my $max_iid=0;
        my $iCount = 0;
        ($rid, $recordInfo) = eq_record_findByRId($dbh,{recordId=>$rid});
        $itemList = eq_item_findByRId($dbh, $rid);
        my $onLoanList =  circ_getLoanListByRid($dbh,$rid);
        foreach my $i(@$itemList){
            $iCount++;
            $i->{'onLoan'} = "";
            $max_iid=$i->{'iid'} if($i->{'iid'}>$max_iid);
            foreach my $ol (@$onLoanList){
                if ($ol->{'barcode'} eq $i->{'barcode'}){
                    $i->{'onLoan'} = 'onLoan';
                }
            }
        }
        my @sorted = sort { $a->{'iid'} cmp $b->{'iid'} || $a->{'copyNo'} cmp $b->{'copyNo'}} @$itemList;
        $template->param(
            rid             => $rid,
            max_iid         => $max_iid,
            recordInfo      => $recordInfo,
            itemList        => \@sorted,        #$itemList,
            iCnt            => ($iCount > 0)? $iCount : 0,
            cat             => $recordInfo->[0]->{'category'},
        );
    }
    
tmpl_write($dbh, $cgi, $cookieList, $template);




sub getShowFieldList {

    #type = "search|brief|full";
    my ($dbh,$type) = @_;
    my $cond="";
    if ($type eq "search"){
        $cond = "showOnSearch";
    }
    elsif ($type eq "brief") {
        $cond = "showOnRecBrief";
    }
    elsif ($type eq "full") {
        $cond = "showOnRecFull";
    }
    else{
        $cond = "showOnSearch";
    }

    my $sth = $dbh->prepare("select id,name, $cond from eq_def where $cond =1");
    my @list;
    $sth->execute();
    while (my $f = $sth->fetchrow_hashref()) {
        push @list, $f;
    }
    return \@list;
}


