#!/usr/bin/perl

#use utf8;
use strict;
use CGI;
use JSON;
use Opals::Context; 
my $dbh = Opals::Context->dbh();
END { $dbh->disconnect(); }

my $itParams=getFormParam();
my $cgi     = CGI->new;
my $typeId =$itParams->{'typeId'};

my $ret= delItemType($dbh,$typeId);

print "Content-type: text/plain\n\n";
print  to_json({status=>$ret,typeId=>$typeId});
#===================================================================================================
sub delItemType{
    my($dbh,$typeId)=@_;
    my $sql_countLib = <<_SQL_;
select  count(*)
from    opl_item
where   typeId = ? && barcode not regexp '^\_\_\_'
_SQL_
my $sql_countTb = <<_SQL_;
select  count(*)
from    tb_items
where   typeId = ? && barcode not regexp '^\_\_\_'
_SQL_
my $sql_countEq = <<_SQL_;
select  count(*)
from    eq_items
where   typeId = ? && barcode not regexp '^\_\_\_'
_SQL_

    my $sth_itemType = $dbh->prepare(<<_SQL_);
delete from opl_itemType
where   id = ?
_SQL_
    my $sth_itemTypeParam = $dbh->prepare(<<_SQL_);
delete from opl_itemTypeParam
where   itemTypeId = ?
_SQL_
  my ($countLib,$countTb,$countEq) =(0,0,0);

        ($countLib) = $dbh->selectrow_array($sql_countLib, undef, $typeId);
        ($countTb) = $dbh->selectrow_array($sql_countTb, undef, $typeId);
        ($countEq) = $dbh->selectrow_array($sql_countEq, undef, $typeId);
        if ($countLib || $countTb || $countEq) {
           return 0; 
        }
        else {
            $sth_itemTypeParam->execute($typeId);
            $sth_itemType->execute($typeId);
            return 1;
        }

}


#===================================================================================================

sub getFormParam{
 my $itParams;
  if ($ENV{'REQUEST_METHOD'} eq "POST") {
        my $json ="";
        while (<STDIN>) {
            $json .= $_;
        }
         $itParams = decode_json($json);
    }

   return $itParams;

}

#===================================================================================================
