#!/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/scm/scmlogger.conf"; 
Log::Log4perl::init($log_conf); 
my $logger = Log::Log4perl->get_logger();
my $current_speed = 100;
# Variables
my $work = 0;
my $username = 'svam'; # set your MySQL username
my $password = 'svam'; # set your MySQL password
my $database = 'SVAMCI30'; # 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";
$logger->debug("Demarrage de SCM Scheduler "); 
 
# sample logging statement
 $SIG{TERM} = sub { $continue = 0 };
 
      while ($continue) {
     #Start the daemon
           sleep(30);
           my $ring_tone_max = get_db_config( "MAX_REPEAT", $dbh);
           my $retry_max =   get_db_config( "MAX_RETRIES", $dbh);
           my $retry_interval_max =   get_db_config( "INT_RETRIES" , $dbh);
           
           $logger->debug("Parametres QOS  de SCM Scheduler ::>  MAX_WAIT ".$ring_tone_max. "  MAX_RETRIES ::> ".$retry_max."  INT_RETRIES ::> ".$retry_interval_max );  
           
            # my $cic_count = get $url; die "Impossible de contacter l URL $url" unless defined $cic_count;
             my $cic_count = 100;
             $logger->debug("$cic_count canaux disponibles.");
                  if($cic_count==0){
                           $logger->warn("Aucun canal disponible. System en attente");
                            
                     }
                    else {
                             $logger->debug("$cic_count  disponibles. System pret a emmettre des appels");  
                             if($cic_count <= $current_speed) {
                               $logger->debug("Le compte des CIC est inferieur au debit des appels, reduction des appels a $cic_count appels.");
                               $current_speed =  $cic_count; 
                             
                             }   
                                  
                             $work =  myDate();
                             $logger->debug("Demarrage d'un cycle d'appel a $work .");
                             
                             my $currentDateTime =  $values[0]." ".$values[1];
                             
                             my @values = split(' ', $work);
                             
                             my $query = "
                                          select  b.item_id_n
		   ,b.event_datetime_d
		   ,b.phone_number_v
		   ,b.entity_v
		   ,b.campaign_id_n
		   ,a.appid
		   ,c.short_code_v
		   ,a.campaign_name_v
		from    master_campaigns_tab a
		  , queues_processor_tab b
		  , iad_senders_tab c
		where a.campaign_id_n = b.campaign_id_n
    and ( ( a.start_date_d<='".$values[0]."' and a.start_time_d<='".$values[1]."'  and b.status_n in ('2','5') ) OR  b.status_n in ('2','5') ) 
    and (  a.char_field_4 = 0 OR  a.char_field_4 IS NULL OR ( a.start_date_d<='".$values[0]."' and a.start_time_d<='".$values[1]."'  and a.char_field_4 = 1)  )
	and (  a.end_date_d is NULL and a.end_time_d is null OR ( concat( a.end_date_d, ' ', a.end_time_d)>'".$currentDateTime."' ))
    and a.status_n not in ('3','9')   
    and a.sender_id_n = c.sender_id_n
	ORDER BY b.event_datetime_d DESC
                                          "   ;
                             
                           #   $logger->warn($query); 
                             my $sth = $dbh->prepare(  $query   )
                                || die "$DBI::errstr";

                            $sth->execute();
                            
                            if ($sth->rows < 0) {
                            
                                $logger->warn("Aucune donnees trouvees en base. Systeme en attente.");
                                
                            }
                            else {
                                # Loop if results found
                                while (my $results = $sth->fetchrow_hashref) {
                                
                                    
                                
                                    $uniqId = luniqid;
                                  # $logger->debug("SESSION ::> $uniqId  Deplacement des donnees dans la table  broadcast_result_tab ");
                                  #  upld_processed_record($dbh, $results->{campaign_id_n},$results->{phone_number_v}, $results->{event_datetime_d},$results->{queue_id_n}, $uniqId,0,2 );
                                    $logger->debug("SESSION ::> $uniqId  Generation du fichier Call"); 
                                    generateCallFile($results->{phone_number_v}, $results->{short_code_v}, $results->{appid}, $results->{campaign_id_n}, $results->{item_id_n},$uniqId, $results->{phone_number_v}, $results->{short_code_v}, $ring_tone_max, $retry_max, $retry_interval_max);   
                                    $logger->debug("SESSION ::> $uniqId  Mise de l'enregistrement de la table Queue."); 
                                    update_queues_record($results->{item_id_n}, $dbh);
                                    
                                    $logger->debug("SESSION ::> $uniqId  MSISDN  ::> ".$results->{phone_number_v}." SHORTCODE ::> ".$results->{short_code_v}."  CAMPAGNE  ::> ".$results->{campaign_name_v}); 
                                    update_campaign_stats($results->{campaign_id_n}, $dbh);
                                }
                                
                                
                            }
                            

                                    $sth->finish;
                                
                            
                            
                            
                         
                         }

     
             





       }
 
 
  
#Return Current Date 
sub myDate {
($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;
}


#Generate call
sub generateCallFile {
      my $ast_outgoing_path = "/var/spool/asterisk/outgoing";
      my $random_number = rand(10000) ;
      my $filename = $_[0]."_".$random_number.".call";
      my $filepath = '/opt/svam/tmp/'.$filename;
      
      #!/usr/local/bin/perl
         open (MYFILE, '>'.$filepath);
        # print MYFILE "Channel: SS7/alpha/".$_[0]." \n";
         print MYFILE "Channel: SIP/".$_[0]." \n";
         print MYFILE "Callerid: ".$_[1]." \n"; 
         print MYFILE "Context: svam \n"; 
         print MYFILE "Extension: 100 \n"; 
         print MYFILE "WaitTime: ".$_[8]." \n";
         print MYFILE "Maxretries: ".$_[9]." \n"; 
         print MYFILE "RetryTime: ".$_[10]." \n";    
         print MYFILE "Setvar: appId=".$_[2]." \n";
         print MYFILE "Setvar: campaignId=".$_[3]." \n";
         print MYFILE "Setvar: queueId=".$_[4]." \n"; 
         print MYFILE "Setvar: sessionId=".$_[5]." \n";
         print MYFILE "Setvar: msisdn=".$_[6]." \n";  
         print MYFILE "Setvar: shortCode=".$_[7]." \n"; 
         print MYFILE "Archive: Yes \n";          

         close (MYFILE) ;

       system("mv $filepath  $ast_outgoing_path") ;

}


sub update_queues_record {

 my $dbh =   $_[1];
 my $query = "UPDATE queues_processor_tab SET status_n=6 WHERE item_id_n='".$_[0]."'";
 my $sth = $dbh->prepare(  $query   ) ;
    $sth->execute(); 
    $sth->finish;  
    
}

sub upld_processed_record {

 my $dbh =   $_[0];
 my $query = "INSERT INTO broadcast_result_tab ( item_id_n, event_datetime_d, campaign_id_n, phone_number_v, issued_date_d, queue_id_n, session_id_v, error_code_n, status_n )
              VALUES (NULL, now(), '".$_[1]."', '".$_[2]."', '".$_[3]."', '".$_[4]."', '".$_[5]."', '".$_[6]."', '".$_[7]."') ";
 my $sth = $dbh->prepare(  $query   ) ;
    $sth->execute();
    $sth->finish;   
    
}

sub get_db_config {

 my $dbh =   $_[1];
 my $query = "SELECT qos_value_v FROM  iad_qos_tab  WHERE  qos_code_v='".$_[0]."'";
 my $sth = $dbh->prepare(  $query   ) ;
    $sth->execute(); 
    my $results = $sth->fetchrow_hashref;
    
    $sth->finish;  
  
   return  $results->{qos_value_v} ;
}


sub update_campaign_stats {

 my $dbh =   $_[1];
 my $query = "UPDATE master_campaigns_tab SET char_field_3=char_field_3+1 WHERE campaign_id_n='".$_[0]."'";
 my $sth = $dbh->prepare(  $query   ) ;
    $sth->execute(); 
    $sth->finish;  
    
}