#!/usr/bin/perl -w

use strict;
use XML::DOM;
use DBI;

my $reqs;

#checking req.pl copy running.
open(LIMIT, "ps ax | grep -v grep | grep -c mnemo.pl |");
while ( <LIMIT> )
{
  chomp;
  $reqs = $_;
}
close(LIMIT);
if ( $reqs > 1 )
{ 
  print "A copy of mnemo.pl is already running. Exiting...\n";    
  exit(); 
}

my $driver = "mysql";
my $opt_user = "";
my $opt_password = "";
my $opt_base = "";
my $socket = "/tmp/mysql.sock"; 
my $appserv = "";
my $localaddress = "";


open(CONF,"../scripts/scripts.conf") or die "Can't open config file!";
my $confparam = "";
my $confvalue;

while( <CONF> )
{
  chomp();
  print $_ . "\n";
  ($confparam,$confvalue)=split(/=/);
  if ( defined($confvalue) )
  {
    if ( $confparam eq "dbuser" )
    {
      $opt_user=$confvalue;
    }
    elsif ( $confparam eq "dbpass" )
    {
	  $opt_password=$confvalue;
	}
    elsif ( $confparam eq "db" )
    {
	  $opt_base=$confvalue;
	}
    elsif ( $confparam eq "appserv" )
    {
      $appserv=$confvalue;
	}
    elsif ( $confparam eq "localaddress" )
    {
      $localaddress=$confvalue;
	}
	else
    {
    }
  }
  else
  {
    print "WARNING: split didn't find '=' in line.\n";
  }
}
close(CONF);

$ENV{"3306"} = "$socket";
my $url = "DBI:$driver:$opt_base:localhost";
my $dbh = DBI->connect("$url", "$opt_user", "$opt_password") || die "Can't connect\n";


my $strtopars = "";

# Create a user agent object
use LWP::UserAgent;
#print "Local Address: ".$localaddress."\n";
@LWP::Protocol::http::EXTRA_SOCK_OPTS = (LocalAddr => $localaddress) if $localaddress ne "";
my $ua = LWP::UserAgent->new;
$ua->agent("ControllerGetMnemo");

while ( $strtopars eq "" )
{
# Create a request
  my $req = HTTP::Request->new(GET => "http://$appserv/MnemoServlet/mnemoservlet");
#     $req->content_type('application/x-www-form-urlencoded');
#     $req->content('match=www&errors=0');

# 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 )
  {
    $strtopars= $res->content;
  }
  else
  {
    print "Can't connect. Check servlet working.\n";
    exit(1);
  }
}
print "Content: \n $strtopars";

my $parser = new XML::DOM::Parser;
my $doc = $parser->parse($strtopars);

my $containers = $doc->getElementsByTagName("container");
my $containers_number = $containers->getLength;

for ( my $i = 0; $i < $containers_number; $i++ )
{
  my $container = $containers->item($i);
  my $container_name = $container->getAttribute("name");
  my $container_time = $container->getAttribute("time");
  print "Name: $container_name, Time: $container_time\n";

  my $query = "SELECT id, time FROM storedData where type='MnemoSVG' and name='$container_name'";
  my $sth = $dbh->prepare($query);
  $sth->execute();
  my $line;
  if ( $line = $sth->fetchrow_arrayref )
  {
    print "ID: " . $$line[0] . "," if $$line[0] ne "";
    print "Time: " . $$line[1] . "\n" if $$line[1] ne "";
    $container->setAttribute("id", $$line[0]);
    if ( $$line[1] < $container_time )
    {
      $container->setAttribute("method", "update");
    }
  }
  else
  {
    $container->setAttribute("method", "insert");
  }
  undef $sth;
}

my $ids = "";
for ( my $i = 0; $i < $containers_number; $i++ )
{
  my $container = $containers->item($i);
  my $container_id = $container->getAttribute("id");
  $ids .= $container_id . ", " if $container_id ne "";
}
$ids .= "0";
print "IDS: $ids\n";
my $query = "DELETE FROM storedData WHERE type='MnemoSVG' AND NOT (id IN ($ids))"; 
print "Query: $query\n";
$dbh->do($query) or die "DELETE failed";

for ( my $i = 0; $i < $containers_number; $i++ )
{
  my $container = $containers->item($i);
  my $container_name = $container->getAttribute("name");
  my $container_time = $container->getAttribute("time");
  my $container_method = $container->getAttribute("method");
  my $container_id = $container->getAttribute("id");
  print "Name: $container_name, Time: $container_time, Method: $container_method, ID: $container_id\n";
  if ( $container_method eq "insert" or $container_method eq "update" )
  {
    my $mnemo = "";
    while ( $mnemo eq "" )
    {
      my $req = HTTP::Request->new(GET => "http://$appserv/MnemoServlet/mnemoservlet?name=$container_name");
      my $res = $ua->request($req);
      if ($res->is_success) {
        $mnemo = $res->content;
      }
      else
      {
        print "Can't connect or no mnemo configured.\n";
        exit(1);
      }
    }
    my $mnemo_quoted = $dbh->quote($mnemo);
    #print "Mnemo:\n" . $mnemo_quoted;
    if ( $container_method eq "insert" )
    {
      my $query = "INSERT INTO storedData(name, time, type, data) VALUES ('$container_name', $container_time, 'MnemoSVG', $mnemo_quoted)";
      $dbh->do($query) or die "INSERT failed";
    }
    elsif ( $container_method eq "update" )
    {
      my $query = "UPDATE storedData SET time='$container_time', data=$mnemo_quoted WHERE id='$container_id'";
      $dbh->do($query) or die "UPDATE failed";
    }
  }
}
$doc->dispose;

undef $dbh;