#!/usr/bin/perl 

BEGIN {
    if (!$ENV{'PERL5LIB'} || !$ENV{'OPALS_CONF'}) {
        exit 1;
    }
}

use strict;
use Time::HiRes qw( time );
use CGI;
use DBI;
use Time::HiRes qw( 
      clock_gettime 
      CLOCK_REALTIME 
      );
use POSIX qw(
    ceil
    floor
);

use Opals::Context;
use JSON;
my $dbh     = Opals::Context->dbh();
my $sql="insert into opl_clickCount(source,sourceID,date,count) values(?,?,?,?) ";

addTabId($dbh);
$dbh->do("truncate table opl_clickCount");
my ($hitCounter)=$dbh->selectrow_array("select val from opl_preference where var='hitCounter'");
my $counterObj=decode_json($hitCounter);

foreach my $src(keys %$counterObj){
    next if($src eq 'pageVisit');
    foreach my $srcID(keys %{$counterObj->{$src}}){
            my $dateFrom=$counterObj->{$src}->{$srcID}->{'since'};
            my $count   =$counterObj->{$src}->{$srcID}->{'count'};
            $dbh->do($sql,undef,$src,$srcID,$dateFrom,$count);
    }
}

############################################################
sub addTabId{
    my ($dbh)=@_;
    my ($portalJson)=$dbh->selectrow_array("select fileData from opl_file where fileName='portalJson'");
    if($portalJson){
        my $changed=0;
        my $portal=from_json($portalJson);
        foreach my $tab (@{$portal->{'tabs'}}){
            if(!defined $tab->{'tabId'}){
                $tab->{'tabId'}=genId();
                $changed=1;
            }
        }
        if($changed){
            open TMP ,">/tmp/tmpPortal.js";    print TMP to_json($portal); close TMP;
            open IN ,"</tmp/tmpPortal.js";
            my $pStr="";
            while(<IN>){
                $pStr .= $_;
            }
            $dbh->do("update opl_file set fileData=? where fileName='portalJson'",undef,$pStr);
        }
    }


}

############################################################
sub genId{
   my $realtime   = clock_gettime(CLOCK_REALTIME);   
   my $num = 1000*clock_gettime(CLOCK_REALTIME)+ ceil(rand()*100000);
   return num_to_b36($num)

}
############################################################
sub num_to_b36 {
    my ($n)=@_;
    use integer;  # so that /= 36 is easy
    my $s = "";
    my @to_b36 = (0 .. 9, 'a' .. 'z');
    do { $s = $to_b36[$n % 36] . $s, $n /= 36 } while $n;
    return $s;
}

exit 0;

