#!/usr/bin/perl

#use utf8;
use strict;
use CGI;
use JSON;

use Opals::Context;
use Opals::BackgroundJobs qw(
    bgjob_create
    bgjob_execute
    bgjob_getStatus
    bgjob_getOutput
    bgjob_process
);

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

my $input   = getJobInfo();

my $cgi     = CGI->new;
my $bcList  = $input->{'bcList'};
my $status  = 1;

$status = createJob($bcList);

print "Content-type: text/plain\n\n";

my $rs={status=>$status};
print   to_json($rs);
#-------------------------------------------------------------
sub createJob{
    my ($bcList)=@_;
    my $jobInfo = {};
    $jobInfo->{"type"}="revertShelfLoc";
    my $itemList=[];
    my $sth =$dbh->prepare("select rid,barcode from opl_item where barcode= ? ");
    foreach my $bc(@$bcList){
        $sth->execute($bc);
        if(my ($rid,$barcode)=$sth->fetchrow_array){
            push @$itemList,{rid=>$rid, barcode=>$barcode}
        }
    }
    my ($jId,$jItemCount)= bgjob_create($dbh,to_json($jobInfo),$itemList);
    bgjob_process($dbh,$jId);
    return ($jId)?1:0;
}
#-------------------------------------------------------------------------------
sub getJobInfo{
  my $fineList=[];
  my $in={};
  if ($ENV{'REQUEST_METHOD'} eq "POST") {
        my $json ="";
        while (<STDIN>) {
            $json .= $_;
        }
        $in = decode_json($json);
   }
   return $in;
}


