#!/usr/bin/perl

use strict;
use CGI;
use JSON;
use Opals::Context;
use Opals::Constant;


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

 
my $genreRec =getGenreRec();
my $gId=save($dbh,$genreRec);
my $cgi = CGI->new;
print "Content-type: text/plain\n\n";

my $rs={status=>1,gId=>$gId};
print   to_json($rs);



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

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

sub save{
    my($dbh,$rec)=@_;
    my $gId=$rec->{"gId"};  
    if(defined $rec->{"gId"} && $gId>0){
        $dbh->do("update opl_genre set title= ?,author=?,introduction=?,modDate=now(),iconUrl=? where gId=?",undef,
                    $rec->{"title"},$rec->{"author"},$rec->{"introduction"},$rec->{"iconUrl"},$rec->{"gId"});
    }
    else{
        $dbh->do("insert into opl_genre set title= ?,author=?,introduction=?, createdDate=now(),iconUrl=?",undef,
                    $rec->{"title"},$rec->{"author"},$rec->{"introduction"},$rec->{"iconUrl"});
        $gId=$dbh->{'mysql_insertid'};
        $rec->{"gId"}=$gId;
    }
    $dbh->do("delete from opl_genreItems where gId=?",undef,$gId);
    $dbh->do("delete from opl_genreGroup where gId=?",undef,$gId);
    my $grpId=1;
    foreach my $rs(@{$rec->{"resourceList"}}){
        $dbh->do("insert into opl_genreGroup set gId=?,groupId=? ,header=?, description=?",undef,
                    $gId,$grpId,$rs->{"header"},$rs->{"description"});
                 
        my $iOrder=0;
        my $ridList={};
        foreach my $book(@{$rs->{"bookList"}}){
            next if(defined $ridList->{$book->{"rid"}});

            $dbh->do("insert into opl_genreItems set gId=?,groupId=?,iOrder=?,rid=?,callNumber=?",undef,
                    $gId,$grpId,$iOrder,$book->{"rid"},$book->{"callNumber"});
            $iOrder++;
            $ridList->{$book->{"rid"}}=1;
        }
        $grpId++;
    }
    return $gId;
}



