#!/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 Opals::Portal qw(
    portal_addPortlet
    portal_updatePortlet
    portal_updateLayout_width
    portal_deletePortlet_excl
);

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

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


my $pid;
my $layoutWidth={};
my $i =0;
my $pidList_new=[];
    while(defined $input->{"type$i"}){
        my $portletInfo={};
        foreach my $f qw(pid type row col ordinal width height){
            $portletInfo->{$f} =$input->{"$f$i"};
        }
        my $row     =$portletInfo->{'row'};
        my $col     =$portletInfo->{'col'};
        my $width   =$portletInfo->{'width'};
        $layoutWidth->{$row}->{$col}=$width;

        if($portletInfo->{'type'} =~ m/rss|newItemList|webLinks|newsEvents|pathfinders|weather|aboutUs|reviewItemList|calendar|html|pfShowcase|libShowcase/){
            foreach my $p qw(nItemShow fieldsShow url showBookCover showDetail zipCode unit content showHolidays html pfIdList title expDate ridList){
                $portletInfo->{'prop'}->{$p}=$input->{"$p$i"} if(defined $input->{"$p$i"});
            }
        }

        $pid=$portletInfo->{'pid'};
        $i++;
        if($pid >= 1000000){ #new portlet
            $pid=portal_addPortlet($dbh,$portletInfo);
        }
        else{
            if($portletInfo->{'type'} ne 'html' || $portletInfo->{'prop'}->{"html"} ne ""){
                $pid=portal_updatePortlet($dbh,$portletInfo);
            }
        }
        push @$pidList_new,$pid;
    }

    
    
    my $savePortletMsg = 1;
       $savePortletMsg = ($pid > 0) ? 1:0;

    my $tid=1;
    my $setWidth =1;
    for my $row( keys %$layoutWidth){
        foreach my $col(keys %{$layoutWidth->{$row}}){
            my $width=$layoutWidth->{$row}->{$col};
            $setWidth = portal_updateLayout_width($dbh,$tid,$row,$col,$width);
        }
    }
    

    $template->param(
        savePortletMsg => $savePortletMsg,
        setWidthMsg    => $setWidth    
    );

portal_deletePortlet_excl($dbh,$pidList_new);


tmpl_write($dbh, $cgi, $cookie, $template);


