#!/usr/bin/perl

use strict;

use XML::DOM;
use DBI;
use LWP::UserAgent;
require "../scripts/connect.pl";
require "../scripts/log.pl";

close(STDERR);

#set this to 1 if you want logs
my $dolog = 0;

my $time_start = time();
my $sync = int(rand(30000)) + 1;
my $query_update   = "UPDATE JSONPollData SET sync=" . $sync . " WHERE sync=0 LIMIT 1000;";
my $query_select   = "SELECT JSONValue FROM JSONPollData WHERE sync = " . $sync . ";";
my $query_rollback = "UPDATE JSONPollData SET sync=0 WHERE sync=" . $sync . ";";
my $query_delete   = "DELETE FROM JSONPollData WHERE sync=" . $sync . ";";
#my $query_delete   = "UPDATE JSONPollData SET sync=-1 WHERE sync=" . $sync . ";";

my $dbh = satisMysqlConnect();

$dbh->do("$query_update");

my $json = "[";
my $sth = $dbh->prepare($query_select);
if (!defined($sth)) {
    $dbh->do("$query_rollback");
    die "Can't prepare: $query_select\n";
}
$sth->execute();
my $line;
my $counter = 0;
my $preadd = 0;
while ($line = $sth->fetchrow_arrayref) {
    my $value = "";
    if($$line[0] ne "") {
        #$$line[2] =~ s/[^ :\-\+,\.a-zA-Z0-9\/]*//g;
        if ($preadd) {$json .= ", ";} else {$preadd = 1};
        $value = $$line[0];
        $value =~ s/[^\x20-\x7e]//g;
        $json .= $value;
    }
    $counter = $counter + 1;
}
$sth->finish();
$json .= "]";
print "Counter: " . $counter . "\n";

if ($counter == 0) {
  sleep 10;
  exit 0;
}

my $appserv = configuration("smonserv");
if($appserv eq "") {
	printf "no smonserv configured\n";
	sleep 86400;
	exit 1;
}
my $strtoparse="";
my $localaddress = configuration('localaddress');
#print "Local Address: ".$localaddress."\n";
@LWP::Protocol::http::EXTRA_SOCK_OPTS = (LocalAddr => $localaddress) if $localaddress ne "";
# Create a user agent object
my $ua = LWP::UserAgent->new;
$ua->agent("ControllerSendPoll ");

while ($strtoparse ne "ok") {
# Create a request
     my $req = HTTP::Request->new(POST => "http://$appserv/scloud/poll");
     $req->content_type('text/json');
     $req->content($json);

# Pass request to the user agent and get a response back
     my $res = $ua->request($req);

# Check the outcome of the response
     if ($res->is_success) {
         $strtoparse= $res->content;
         print "Response: " . $strtoparse . "\n";
         sleep(1);
     } else {
         print "Can't connect. Check servlet working.\n";
         sleep(1);
     }
}

$dbh->do("$query_delete");

$dbh->disconnect();

my $time_stop = time();
my $time_delta = $time_stop - $time_start;
print "Execution time: " . $time_delta . " sec.\n";
if ( $time_delta > 0 and $time_delta < 30 ) {
  sleep 30-$time_delta;
}
