#!/usr/bin/perl

use strict;
use CGI;

use Opals::Context;
use Opals::Template_ajax qw(
    tmpl_read
    tmpl_write
);
use Opals::Locale qw(
    loc_getMsgFile
    loc_write
);
use POSIX qw(
  ceil
  strftime
);

use Opals::Portal qw(
    portal_addPortlet
    portal_updatePortlet
    portal_updateLayout_width
    portal_deletePortlet_excl
);

use Opals::RSS;
 
my $dbh = Opals::Context->dbh();
END { $dbh->disconnect(); }
use Time::HiRes qw(time);

my $cgi = CGI->new;
my $input = $cgi->Vars();
my ($permission, $cookie, $template) = tmpl_read(
    {
        dbh             => $dbh,
        cgi             => $cgi,
        tmplFile        => 'ajax/portlet/savePortlet.tmpl',
    }
);

if ($permission && $permission->{'pref_edit'}) {
     my @lt = localtime;
    my $postStr= strftime("%Y%m%d%H%M%S", @lt);
    my $portalJson =$input->{"portalJson"};

# in MySQL shell, to retrieve the datetime of the file use following sql
# select from_unixtime(cast(left(replace(fileName,"portalJson_",""),10) as UNSIGNED )) as date  from opl_file where fileName regexp "portalJson_" ;
#
        my $bkFileName  =sprintf("portalJson_%s",$postStr) ;
        $bkFileName =~ s/\.//g;


        $dbh->do("update opl_file set fileName='$bkFileName' where filename='portalJson'"); 
        my $sth = $dbh->prepare(<<_STH_);
    insert into  opl_file
    set     mimeType = 'text/plain',
            fileData = ?,
            fileType='text/javascript',
            fileName='portalJson',
            fRealName='portalJson'
_STH_

        $sth->execute($portalJson);
        $sth->finish;
}
tmpl_write($dbh, $cgi, $cookie, $template);
