#!/usr/bin/perl 

BEGIN {
    if (!$ENV{'PERL5LIB'} || !$ENV{'OPALS_CONF'}) {
        print "updateing srchLog...\n";
        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 $stats={pageVisit=>1,portalTab=>{},pf=>{},topicWall=>{},genre=>{}};
my ($today)=$dbh->selectrow_array("select DATE(now())");
my ($hitCounter)=$dbh->selectrow_array("select val from opl_preference where var='hitCounter'");
if($hitCounter=~ m/\d+/){
    $stats->{'pageVisit'}=$hitCounter;
     my ($portalJson)=$dbh->selectrow_array("select fileData from opl_file where fileName='portalJson'");
     if($portalJson){
        my $portal=from_json($portalJson);
        foreach my $tab (@{$portal->{'tabs'}}){
            my $tabId=genId();
            $tab->{'tabId'}=$tabId;
            $stats->{'portalTab'}->{$tabId}={since=>$today,count=>1};
        }
        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);
     }
    #pf
    my $pfIdArr=$dbh->selectcol_arrayref("select pfId from pf_record");
    foreach my $pfId(@$pfIdArr){
        $stats->{'pf'}->{$pfId}={since=>$today,count=>1};
    }
    #Genre
    my $gIdArr=$dbh->selectcol_arrayref("select gId from opl_genre");
    foreach my $gId(@$gIdArr){
        $stats->{'genre'}->{$gId}={since=>$today,count=>1};
    }
   #topic Wall
    my $cidArr=$dbh->selectcol_arrayref("select cid from opl_classif");
    foreach my $cid(@$cidArr){
        $stats->{'topicWall'}->{$cid}={since=>$today,count=>1};
    }

    $dbh->do("update opl_preference set val =? where var='hitCounter'",undef,to_json($stats));


    
}

############################################################
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;

