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

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*10; # ten minutes

($sms, $confirmed, $pc) = get_sms($start_t1, $end_t);

if ($sms>10 && $confirmed<$sms/2) {
my @tolist = ('support@provider.com');
my $email = Email::Simple->create(
    header => [
      From    => 'alarm@provider.com',
      Subject => "WNAM SMS PROBLEM",
    ],
    body => "WNAM SMS check last 10 minutes: SMS sent: $sms, confirmed: $confirmed, ratio: $pc\n",
  );

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

}

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);
  }
