#!/usr/bin/perl 
##########################################################
#
#
#
#

use warnings;
use LWP::Simple;
use Log::Log4perl;
use DBI;
use Data::Uniqid qw ( suniqid uniqid luniqid );

Proc::Daemon::Init; 



my $continue = 1;  
my $uniqId = 0;
#my $url = 'http://10.18.30.2/monitor/monit_test.php'; 
my $log_conf = "/opt/svam/scripts/scc/scc.conf"; 
Log::Log4perl::init($log_conf); 
my $logger = Log::Log4perl->get_logger();
my $current_speed = 100;
# Variables
my $work = 0;

$logger->debug("Demarrage de SCM Scheduler "); 
 
# sample logging statement
 $SIG{TERM} = sub { $continue = 0 };
 
      while ($continue) {
     #Start the daemon
           sleep(10);
		   my $stdDateTime = stdTime();
		   my $queuesLogFile = "/var/log/asterisk/queue_log";
		   my $lastnoFile = "/var/log/asterisk/lastno";
		   #system("/bin/cat /var/log/asterisk/queue_log >  ".$queuesLogFile);
		   #system("/bin/cat /dev/null > /var/log/asterisk/queue_log ");
		   
		   my $lastno = `cat $lastnoFile `;
		   chomp $lastno;
		    
		   
		   $lastno =  $lastno + 0;
		   $logger->debug(" PRECEDENT IDENTIFIANT  ::>  ".$lastno  ); 
		   
		   my $grepRes = `grep CONNECT  $queuesLogFile`;
		   open(my $fh, '>', '/var/log/asterisk/work.log') or die "Could not open file $!";
		   print $fh $grepRes;
		   close $fh;

		   
		   open my $queueCDRFile, '</var/log/asterisk/work.log' or die "Can't open the file: $!";
		   
		  
		   my $unixTimeStamp =0;
		   while (my $line = <$queueCDRFile>) {
               chomp $line;
			   
			   my ($unixTimeStamp,$uniqId,$application,$agentId,$eventname,$field1,$field2,$field3 ) = split /\|/,$line ;
			   chomp $unixTimeStamp;
			   $logger->debug(" CURRENT  ".$unixTimeStamp); 
			   if($unixTimeStamp gt $lastno ) {
			   

			       my $cmd = "grep -h $uniqId /var/log/asterisk/queue_log | grep ENTERQUEUE | cut -d '|' -f7";
			   
			       my $callerId = `$cmd`;
			       chomp $callerId;
			       chomp $agentId;
			       chomp $uniqId;
			       $logger->debug(" ENREGISTREMENT DE  CALLERID ".$callerId." ANSWER_AGENT ".$agentId." UNIQUE_ID ".$uniqId ); 
			       upld_incoming_call_record($logger, $callerId, $agentId, 0, 0);
				   $logger->debug(" ENREGISTREMENT DE  CALLERID ".$callerId." ANSWER_AGENT ".$agentId." UNIQUE_ID ".$uniqId." TERMINE" ); 
			        my $res = `echo $unixTimeStamp > $lastnoFile `;
			   }   
               
           }
          close $queueCDRFile or die "Can't close Queue CDR File: $!";
		  
		  
           
          # $logger->debug("Parametres QOS  de SCM Scheduler ::>  MAX_WAIT ".$ring_tone_max. "  MAX_RETRIES ::> ".$retry_max."  INT_RETRIES ::> ".$retry_interval_max );  
           
           

     
             





       }
 
 
  



sub stdTime {
($seconds, $minutes, $hours, $day, $month, $year) = localtime();
$year += 1900;
$month += 1;
$date = sprintf("%04d%02d%02d-%02d%02d%02d", $year, $month, $day, $hours, $minutes, $seconds);
return $date;
}


sub upld_incoming_call_record {

 my $dbh = getDBConnection();
 my $logger =   $_[0];
 my $query = "INSERT INTO scc_call_history_tab ( call_id_n, event_datetime_d, from_callerid_v, to_number_v, online_status_n, status_n )
              VALUES (NULL, now(), '".$_[1]."', '".$_[2]."', '".$_[3]."', '".$_[4]."') ";
 my $sth = $dbh->prepare(  $query   ) ;
 $logger->debug($query);
    $sth->execute();
    $sth->finish;
   closeDBConnection($dbh, $logger);
}


sub getDBConnection {

	my $username = 'svam'; # set your MySQL username
	my $password = 'svam'; # set your MySQL password
	my $database = 'sp_callcenter'; # set your MySQL database name
	my $server = 'localhost'; # set your server hostname (probably localhost)
	my $dbh = DBI->connect("DBI:mysql:$database;host=$server", $username, $password)
		|| die "Could not connect to database: $DBI::errstr";

  return $dbh;
}



sub closeDBConnection {
my $dbh =   $_[0];
my $logger = $_[1];

$dbh->disconnect
    or $logger->debug("Disconnection failed: $DBI::errstr");


}
