#!/usr/bin/perl

#use utf8;
use strict;
use CGI;

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

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

my $cgi      = CGI->new;
my $input = $cgi->Vars();
my ($startBc,$rangeId,$numf852Add);
$startBc    = $input->{'startBc'};
$rangeId    = $input->{'rid'};
$numf852Add = $input->{'n'};

my ($permission, $cookie, $template) = tmpl_read(
    {
        dbh             => $dbh,
        cgi             => $cgi,
        tmplFile        => 'ajax/marc21/getAvailBcList.tmpl',
        reqPermission   => 'marc_edit',
    }
);
if ($permission && $permission->{'marc_edit'}) {
 
    my $bcList     = getBarcodeList($dbh,$startBc,$rangeId,$numf852Add);
    $template->param(bcList =>$bcList  );
}
tmpl_write($dbh, $cgi, $cookie, $template);

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

sub getBarcodeList{
    my ($dbh,$startBc,$rid,$n) = @_;

    my $sql = <<_STH_;
select      barcode  
from        opl_bcmRange r     inner join opl_bcmBc s on s.rid = r.rid   
where       r.rid = ? && 
            s.status = 'available' && 
            pending = -1 && 
            barcode >=?
order by    barcode 
_STH_

if(defined $n && $n>0){
  #  $sql .= " limit $n";
}
    
    my $sth = $dbh->prepare($sql);
    $sth->execute($rid,$startBc);
    my  @bcList =();
    while (my $barcode = $sth->fetchrow_array) {
         my ($isUsedBc) = $dbh->selectrow_array(<<_STH_);
select      count(barcode)  
from        opl_item    
where       barcode = '$barcode' && available=1
_STH_
        if(!$isUsedBc){
            push @bcList , {barcode=>$barcode};
            $n--;
            if($n ==0){
                return \@bcList;
            }
        }
    }

    $sth->finish;
    return \@bcList;
}



