#!/usr/bin/perl
use lib '/var/www/html/test-scb.impelsys.com/crons/reader_crons'; 
use rd_dimension;
use rd_summary;
use rd_ccr_summary;
use Class::Date;
use Date::Simple(':all');
use POSIX;
require 'db_config.pl';
require 'global_function_library.pl';

#####
#Author    : Harish Kumar
#Date	   : 05th Jan 2010
#Desc	   : Purpose of this process is to create the reader related data -Dimension tables
###################

sub mailError
######
# Send mail only if any error is found
#
{
	my ($dbConn, $errorMsg) = @_;
	#$errorMsg = "processed for date range $ls_end_date";
	######
	# Send mail only if any error is found
	#
	if(length($errorMsg) gt 0) {
		$sqlTokens = "SELECT `key`, value FROM iplat_configurations WHERE category='iPublishCentral' AND configtype='REPORT_CRON_TOKEN'";
		$lhQuery = $dbConn->prepare($sqlTokens) or $errorMsg .= "Error:Preparing MYSQL query failed: $DBI::errstr $sqlTokens\n";
		$lhQuery->execute() or $errorMsg .= "Error:Preparing MYSQL query failed: $DBI::errstr\n";
		while (@results = $lhQuery->fetchrow_array()) {
		if($results[0] eq 'IPC_CRON_STATUS_MAIL_TO_IDS') {
		        @toMailIds = split(',' , $results[1]);
		        $mailToId = "";
		        $mailCcId = "";
		        foreach $mailId (@toMailIds) {
		        	if($mailToId eq "") {
		        		$mailToId = $mailId;
		        	}
			        else {
			        	if( $mailCcId eq "") {
			              		$mailCcId = $mailId;
            				}
				        	else {
				        		$mailCcId = $mailCcId . "," . $mailId;
				        	}
				}
		        } # end of for loop
      	}
      	elsif($results[0] eq 'IPC_CRON_ADMIN_MAIL_IDS') {
        	$mailFromId = $results[1];
      	}
      	elsif($results[0] eq 'IPC_CRON_MAIL_BODY_TEMPALTE') {
        	$mailBodyTemplate = $results[1];
      	}
      	elsif($results[0] eq 'IPC_CRON_MAIL_SUBJECT_TEMPALTE') {
        	$mailSubjectTemplate = $results[1];
                $codePath = $ENV{PWD};
                if($codePath =~ m/sites\/(.*?)\//) {
                        $mailSubjectTemplate .= ",SiteCode:".$1."";
                }
      	}
      	else {
      		# All tokens will begin with { and end with }, if token is not above matched case then it will be a token
		@arrCronTokens[$tokenIndex] = $results[0];
        	$tokenIndex++;
      	}
    	}

	$mailSubjectTemplate = parseToken($mailSubjectTemplate,$errorMsg, @arrCronTokens);
    	$mailBodyTemplate = parseToken($mailBodyTemplate,$errorMsg, @arrCronTokens);
    	my %arrMailCredentials = ();
    	$arrMailCredentials{"mailFrom"} = $mailFromId;
    	$arrMailCredentials{"mailTo"} = $mailToId;
    	$arrMailCredentials{"mailReply"} = $mailFromId;
    	$arrMailCredentials{"mailCc"} = $mailCcId;
    	$arrMailCredentials{"mailBcc"} = "";
    	$arrMailCredentials{"mailSubject"}= $mailSubjectTemplate;
    	$arrMailCredentials{"mailHtmlBody"} = $mailBodyTemplate;
    	$arrMailCredentials{"mailPlainBody"} = "";
    	$arrMailCredentials{"mailAttachment"} = "";
    	sendAlertMail(%arrMailCredentials);
  	}
	######
	return 1;	
}


# Variables used in the error handling & reporting by mail
   my $errorMsg = "";
   my $mailToId = "";
   my $mailCcId = "";
   my $mailFromId = "";
   my $mailSubjectTemplate = "";
   my $mailBodyTemplate = "";
   my @arrCronTokens = ();
   my $tokenIndex = 0;
   my $queryResult = 0;
   my $sqlDelete = "";
####  
   my $sql;
   my $rowsAffected;
   my $today = "";
   my $objAffiliate;

   ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst)=localtime(time);
   my $startTime  = time();

   $rowsAffected = 0;
   $sql = "";
   $isArchivedData = 0;
   #$parseStartDate = today();
   #$parseStartDate = $parseStartDate - 1;
   #$parseEndDate = $parseStartDate;

    my $parseStartDate = "";
    my $parseEndDate = "";
    my $tmpDate = "";

    if(!defined($ARGV[0])){
        $parseStartDate = today();
        $parseStartDate = $parseStartDate-1;
        $parseEndDate = $parseStartDate;
    }else{
        if($#ARGV == 0){
            $parseStartDate = Date::Simple->new($ARGV[0]);
            # if invalid date halt
            if(!defined($parseStartDate)){
              die "\nPlease input vaild dates in specified format\nusage: perl <program.pl> YYYY-MM-DD YYYY-MM-DD\n";
            }
            $parseEndDate = $parseStartDate;
        }
        if($#ARGV == 1){
            $parseStartDate = Date::Simple->new($ARGV[0]);
            $parseEndDate = Date::Simple->new($ARGV[1]);
            # if invalid date halt
            if(!defined($parseStartDate)){
                die "\nPlease input vaild dates in specified format\nusage: perl <program.pl> YYYY-MM-DD YYYY-MM-DD\n";
            }
            # if invalid date halt
            if(!defined($parseEndDate)){
                die "\nPlease input vaild dates in specified format\nusage: perl <program.pl> YYYY-MM-DD YYYY-MM-DD\n";
            }

            if($parseStartDate > $parseEndDate){
                $tmpDate = $parseStartDate;
                $parseStartDate = $parseEndDate;
                $parseEndDate = $tmpDate;
            }
        }
    }


   $codePath = $ENV{PWD};
   $siteCode = "";
   if($codePath =~ m/sites\/(.*?)\//) {
    $siteCode = $1;
   }
   printf "\nStarted the ETL for Reader Dimension,Fact & Summary for Reports (%4d-%02d-%02d %02d:%02d:%02d)\n",$year+1900,$mon+1,$mday,$hour,$min,$sec;
   #object for dimension subroutine
   $objReaderDim        = new rd_dimension($eupConnection, $siteCode, $parseStartDate, $parseEndDate);
   $objReaderSummary    = new rd_summary($eupConnection, $siteCode, $parseStartDate, $parseEndDate);
   $objReaderCcrSummary = new rd_ccr_summary($eupConnection, $siteCode, $parseStartDate, $parseEndDate);


   # --------- Dimension Tables ---------------------------

   $errorMsg = $objReaderDim->populateAccessDateDimension();
   if(length($errorMsg) gt 0) {
     mailError($eupConnection,$errorMsg);
     die();
   }
     
   $errorMsg = $objReaderDim->populateBookDetailsDimension();
   if(length($errorMsg) gt 0) {
     mailError($eupConnection,$errorMsg);
     die();
   }

   $errorMsg = $objReaderDim->populateEupUsers();
   if(length($errorMsg) gt 0) {
     mailError($eupConnection,$errorMsg);
     die();
   }


   $errorMsg = $objReaderDim->populateEupUserTypes();
   if(length($errorMsg) gt 0) {
     mailError($eupConnection,$errorMsg);
     die();
   }

   $errorMsg = $objReaderDim->populateCountryDimension();
   if(length($errorMsg) gt 0) {
     mailError($eupConnection,$errorMsg);
     die();
   }
 
   $errorMsg = $objReaderDim->populateInstitutionDimension();
   if(length($errorMsg) gt 0) {
     mailError($eupConnection,$errorMsg);
     die();
   }

   $errorMsg = $objReaderDim->populateMediaActionDimension();
   if(length($errorMsg) gt 0) {
     mailError($eupConnection,$errorMsg);
     die();
   }

   $errorMsg = $objReaderDim->populateProductDetailsDimension();
   if(length($errorMsg) gt 0) {
     mailError($eupConnection,$errorMsg);
     die();
   }


   $errorMsg = $objReaderDim->populateReaderMediaDimension();
   if(length($errorMsg) gt 0) {
     mailError($eupConnection,$errorMsg);
     die();
   }


   $errorMsg = $objReaderDim->populateReaderUserActivityDimension();
   if(length($errorMsg) gt 0) {
     mailError($eupConnection,$errorMsg);
     die();
   }


   $errorMsg = $objReaderDim->populateUserAgentDimension();
   if(length($errorMsg) gt 0) {
     mailError($eupConnection,$errorMsg);
     die();
   }


   $errorMsg = $objReaderDim->populateSearchTermDimension();
   if(length($errorMsg) gt 0) {
     mailError($eupConnection,$errorMsg);
     die();
   }

 
   # -----------------FACT TABLES ------------------
   
   $errorMsg = $objReaderDim->populateReaderClickFact();
   if(length($errorMsg) gt 0) {
     mailError($eupConnection,$errorMsg);
     die();
   }

   $errorMsg = $objReaderDim->populateReaderMediaFact();
   if(length($errorMsg) gt 0) {
     mailError($eupConnection,$errorMsg);
     die();
   }

  
   $errorMsg = $objReaderDim->populateReaderSearchFact();
   if(length($errorMsg) gt 0) {
     mailError($eupConnection,$errorMsg);
     die();
   }

   
   #----------------- Summary Tables -------------------

  
   $errorMsg = $objReaderSummary->readerSummaryDate();
   if(length($errorMsg) gt 0) {
     mailError($eupConnection,$errorMsg);
     die();
   }
   
   $errorMsg = $objReaderSummary->readerSummaryDateBook();
   if(length($errorMsg) gt 0) {
     mailError($eupConnection,$errorMsg);
     die();
   }

   $errorMsg = $objReaderSummary->readerSummaryDateBookPage();
   if(length($errorMsg) gt 0) {
     mailError($eupConnection,$errorMsg);
     die();
   }

   $errorMsg = $objReaderSummary->readerSummaryDateBookActivity();
   if(length($errorMsg) gt 0) {
     mailError($eupConnection,$errorMsg);
     die();
   }

   $errorMsg = $objReaderSummary->readerSummaryDateBookCountryCity();
    if(length($errorMsg) gt 0) {
     mailError($eupConnection,$errorMsg);
     die();
   }

   $errorMsg = $objReaderSummary->readerSummaryDateBookCountry();
   if(length($errorMsg) gt 0) {
     mailError($eupConnection,$errorMsg);
     die();
   }

   $errorMsg = $objReaderSummary->readerSummaryDateBookInstitute();
   if(length($errorMsg) gt 0) {
     mailError($eupConnection,$errorMsg);
     die();
   }
   
   $errorMsg = $objReaderSummary->readerSummaryDateBookUserAgents();
   if(length($errorMsg) gt 0) {
     mailError($eupConnection,$errorMsg);
     die();
   }

   $errorMsg = $objReaderSummary->readerSummaryDateBookUserTypes();
   if(length($errorMsg) gt 0) {
     mailError($eupConnection,$errorMsg);
     die();
   }

   $errorMsg = $objReaderSummary->readerSummaryDateCountry();
   if(length($errorMsg) gt 0) {
     mailError($eupConnection,$errorMsg);
     die();
   }

   $errorMsg = $objReaderSummary->readerSummaryDateCountryCity();
   if(length($errorMsg) gt 0) {
     mailError($eupConnection,$errorMsg);
     die();
   }

   $errorMsg = $objReaderSummary->readerSummaryDateInstitute();
   if(length($errorMsg) gt 0) {
     mailError($eupConnection,$errorMsg);
     die();
   }

   $errorMsg = $objReaderSummary->readerSummaryDateUserAgents();
   if(length($errorMsg) gt 0) {
     mailError($eupConnection,$errorMsg);
     die();
   }
 
   $errorMsg = $objReaderSummary->readerSummaryDateUserTypes();
   if(length($errorMsg) gt 0) {
     mailError($eupConnection,$errorMsg);
     die();
   }

   $errorMsg = $objReaderSummary->readerSummaryAlltime();
   if(length($errorMsg) gt 0) {
     mailError($eupConnection,$errorMsg);
     die();
   }


   #---- Search Summary   --------------
  
   $errorMsg = $objReaderSummary->readerSummarySearchDateBook();
   if(length($errorMsg) gt 0) {
     mailError($eupConnection,$errorMsg);
     die();
   }

   $errorMsg = $objReaderSummary->readerSummarySearchDate();
   if(length($errorMsg) gt 0) {
     mailError($eupConnection,$errorMsg);
     die();
   }

  
   #---- Media Library Summary   --------------

   $errorMsg = $objReaderSummary->readerSummaryMediaAllTitles();
   if(length($errorMsg) gt 0) {
     mailError($eupConnection,$errorMsg);
     die();
   }


   $errorMsg = $objReaderSummary->readerSummaryMediaByTitles();
   if(length($errorMsg) gt 0) {
     mailError($eupConnection,$errorMsg);
     die();
   }



   #-------------------  Counter Report (CCR)--------------------

   $errorMsg = $objReaderCcrSummary->readerCcrBr2Fact();
   if(length($errorMsg) gt 0) {
     mailError($eupConnection,$errorMsg);
     die();
   }

   $errorMsg = $objReaderCcrSummary->readerCcrBr2SummMonthBook();
   if(length($errorMsg) gt 0) {
     mailError($eupConnection,$errorMsg);
     die();
   }

   $errorMsg = $objReaderCcrSummary->readerCcrBr2SummMonthBookPage();
   if(length($errorMsg) gt 0) {
     mailError($eupConnection,$errorMsg);
     die();
   }
   
   
   $errorMsg = $objReaderCcrSummary->readerCcrBr2SummInstMonthBook();
   if(length($errorMsg) gt 0) {
     mailError($eupConnection,$errorMsg);
     die();
   }

   $errorMsg = $objReaderCcrSummary->readerCcrBr2SummInstMonthBookPage();
   if(length($errorMsg) gt 0) {
     mailError($eupConnection,$errorMsg);
     die();
   }


   $errorMsg = $objReaderCcrSummary->readerCcrBr2SummNormalMonthBook();
   if(length($errorMsg) gt 0) {
     mailError($eupConnection,$errorMsg);
     die();
   }
   
   
   $errorMsg = $objReaderCcrSummary->readerCcrBr2SummNormalMonthBookPage();
   if(length($errorMsg) gt 0) {
     mailError($eupConnection,$errorMsg);
     die();
   }

   $errorMsg = $objReaderCcrSummary->readerCcrBr4Fact();
   if(length($errorMsg) gt 0) {
     mailError($eupConnection,$errorMsg);
     die();
   }

   $errorMsg = $objReaderCcrSummary->readerCcrBr4SummInstMonth();
   if(length($errorMsg) gt 0) {
     mailError($eupConnection,$errorMsg);
     die();
   }
 

   $errorMsg = $objReaderCcrSummary->readerCcrBr3SummInstMonthBook();
   if(length($errorMsg) gt 0) {
     mailError($eupConnection,$errorMsg);
     die();
   }

  

   $errorMsg = $objReaderCcrSummary->readerCcrBr5Fact();
   if(length($errorMsg) gt 0) {
     mailError($eupConnection,$errorMsg);
     die();
   }

   $errorMsg = $objReaderCcrSummary->readerCcrBr5SummMonthBook();
   if(length($errorMsg) gt 0) {
     mailError($eupConnection,$errorMsg);
     die();
   }

   $errorMsg = $objReaderCcrSummary->readerCcrBr5SummMonthBookInst();
   if(length($errorMsg) gt 0) {
     mailError($eupConnection,$errorMsg);
     die();
   }


   
  

   $eupConnection->disconnect();        
   ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst)=localtime(time);
   my $timeDiff = time() - $startTime ;
   my $difMin = int($timeDiff / 60);
   my $diffSec = sprintf("%02d", $timeDiff - 60 * $difMin);

   printf "\nEnd of ETL for warehousing of Dimension & Fact Table End Time:%4d-%02d-%02d %02d:%02d:%02d [%2d\:%02d]\n",$year+1900,$mon+1,$mday,$hour,$min,$sec,$difMin,$diffSec;
   
;
