#!/usr/bin/perl -w

use MongoDB;
use Email::Sender::Simple qw(sendmail);
use Email::Sender::Transport::SMTP qw();
use Email::Simple::Creator;
sub get_sms;
sub get_sessions;
sub get_current_s;
sub get_current_c;

my $client = MongoDB->connect();
my $db = $client->get_database('wnam_db');
my $smsStat = $db->get_collection('smsStat');

$end_t = time()*1000;
$start_t1 = $end_t - 1000*60*60;
$start_t2 = $end_t - 1000*60*60*24;

#print $start_t1."  ".$end_t."\n";

my $data;

($sms, $confirmed, $pc) = get_sms($start_t1, $end_t);
$data = sprintf("SMS last hour: total $sms, confirmed $confirmed (%.1f%%)\n", $pc);
($sms, $confirmed, $pc) = get_sms($start_t2, $end_t);
$data .= sprintf("SMS last 24 hours: total $sms, confirmed $confirmed (%.1f%%)\n", $pc);

($rx, $tx, $sess) = get_sessions($start_t1, $end_t);
$data .= sprintf("Sessions last hour: $sess, RX %d Mb, TX %d Mb\n", $rx/1024/1024, $tx/1024/1024);
($rx, $tx, $sess) = get_sessions($start_t2, $end_t);          
$data .= sprintf("Sessions last 24 hours: $sess, RX %d Mb, TX %d Mb\n", $rx/1024/1024, $tx/1024/1024);

($sess_c, $sess_t) = get_current_s();
$data .= sprintf("Online sessions: $sess_c, total sessions: $sess_t\n");

($cust) = get_current_c();
$data .= sprintf("Total customers: $cust\n");

$data .= sprintf("System:%s", `w`);

$data =~ s/\n/\n\n/g;

my @tolist = ('support@provider.com');
my $email = Email::Simple->create(
    header => [
      From    => 'alarm@provider.com',
      Subject => "WNAM status",
    ],
    body => "$data",
  );

sendmail($email, { to => \@tolist});

sub get_sessions(){
 my ($start_t, $end) = @_;
 my $sessions = $db->get_collection('sessions');
 my $out = $sessions->aggregate([
   {'$match' => {'endTime' => { '$gt' => $start_t, '$lte' => $end_t }} },
   {'$group' => {'_id' => '$siteId', 'sent' => { '$sum' => '$sent' }, 'received' => { '$sum' => '$received' }, 'sessions' => {'$sum' => 1} } }
   ]);
  
 my ($rx, $tx, $sess);  
 $rx=0; $tx=0; $sess=0;
 while (my $doc = $out->next) {
  $rx=$rx+$doc->{'received'};
  $tx=$tx+$doc->{'sent'};
  $sess=$sess+$doc->{'sessions'};
  }
 return ($rx, $tx, $sess);
 }

sub get_sms() {
  my ($start_t, $end) = @_;
  my $data_hour = $smsStat->find({'time' => { '$gt' => $start_t, '$lte' => $end_t }});
  my $sms=0, $confirmed=0;
  while (my $doc = $data_hour->next){
    $sms++;
    if ($doc->{'confirmed'} == 1) { $confirmed++; }
    }
  my $pc=0;
  if ($sms>0) { $pc=100*$confirmed/$sms; }
  return ($sms, $confirmed, $pc);
  }

sub get_current_s(){
 my $sessions = $db->get_collection('sessions');
 my $data = $sessions->find({'endTime' => 0});
 my $s=0;
 while (my $doc = $data->next){
  $s++;
  }
 my $t = $sessions->count; 
 return ($s, $t);
 }                      

sub get_current_c(){
 return $db->get_collection('customers')->count;
 }                      
 