#!/usr/bin/perl -w

use lib '/www/opals/module';
#use Opals::Context("/etc/opals/conf/oc_oc");
#use Opals::Context("/etc/opals/conf/wpc_wpc");
use Opals::Context("/etc/opals/conf/_MY_SITE_");
use strict;
use DBI;
use JSON;
use POSIX qw(
    ceil
);
my $dbh = Opals::Context->dbh();
END {
    if ($dbh) {
        $dbh->disconnect();
    }
}

$| = 1;
# Codes start...

my $aboutUs="";
my $sth = $dbh->prepare(<<_SQL_);
select * from opl_portlet order by cid,ordinal ; 
_SQL_

my $sth_prop = $dbh->prepare(<<_SQL_);
select var,convert(cast(convert(val using  latin1) as binary) using utf8) val from opl_portletProp where pid=?
_SQL_


    $sth->execute;
    my @tab=();
    my $portal={aboutUs=>""};
    while( my ($pid,$cid,$ordinal,$type) = $sth->fetchrow_array) {
         $sth_prop->execute($pid);
         $type="newitems" if($type eq "newItemList");
         $type="newsevent" if($type eq "newsEvents");
         $type="reviewitems" if($type eq "reviewItemList");
         $type="pathfinder" if($type eq "pathfinders");
         $type="weblink" if($type eq "webLinks");
         $type="libraryhours" if($type eq "libraryHours");
         $type="portlethtml" if($type eq "html");
         $type="libshowcase" if($type eq "libShowcase");
         $type="pfshowcase" if($type eq "pfShowcase");
         my $portlet={type=>$type,params=>{}};
         $portlet->{"params"}->{"events"}=[]if($type eq "calendar");
         while(my ($var,$val)=$sth_prop->fetchrow_array){
            if($type eq "aboutUs"){
                $portal->{"aboutUs"}=$val;
                next;
            }
            else{
                $var="rssUrl" if($var eq 'url' && $type eq 'rss');
                $var="scTitle" if($var eq 'title' && $type =~ m/pfshowcase|libshowcase/);
                $portlet->{'params'}->{$var}=$val;
            }
         }
         if($type ne "aboutUs"){

            $tab[$cid-1]=() if(!$tab[$cid-1]);
            push @{$tab[$cid-1]},$portlet;
         }
         
    }  
    $portal->{"tabs"} =[{name=>"Tab 1",content=>\@tab}] ;
    my $json = to_json($portal,{utf8 => 1});
    #print "$json\n";

    #$dbh->do("update opl_file set fileName='$bkFileName' where filename='portalJson'"); 

   
   $sth = $dbh->prepare(<<_STH_);
replace into  opl_file
set     mimeType = 'text/plain',
        fileData = ?,
        fileType='text/javascript',
        fileName='portalJson',
        fRealName='portalJson'
_STH_

  $sth->execute($json);
#print "$json\n";
    $sth->finish;






#////////////////////////////////////////////////////////////////////////////
