#!/usr/local/bin/perl -w

use strict; # preventing my program from doing bad things
use DBI; # http://dbi.perl.org

# configuration
my $queue_db = "ljimport";
my $queue_host = "localhost";
my $queue_login = "root";
my $queue_pass = "";
my $speed_throttle = "2"; # seconds

# main loop, throttled
while (1) {
  process_queue(); # process new requests for import if any
  sleep ($speed_throttle); # sleep for a while
}

sub process_queue {
  my $row;
  my $row1;
  my $history_id;
  my $sth2;
  
  my $dbh = DBI->connect(
     "DBI:mysql:$queue_db:$queue_host",
      $queue_login, $queue_pass,
      {RaiseError => 0, AutoCommit => 1}
    ) || die "Can't open database connection: $DBI::errstr";
  
  my $sth = $dbh->prepare("SELECT * from iqueue");
  $sth->execute;
  while ($row = $sth->fetchrow_hashref) {
    my $sth1 = $dbh->prepare (
      "SELECT * from iqueue where
         local_user = '" . $row->{'local_user'} . "'
         order by local_user desc, importid desc
         limit 1");
    $sth1->execute; # find last user request for import
    $row = $sth1->fetchrow_hashref;

    $sth2 = $dbh->prepare (
      "insert into ihistory values (''," .
        "'" . $row->{'remote_site'} . "', " .
        "'" . $row->{'remote_user'} . "', " .
        "'" . $row->{'local_site'} . "', " .
        "'" . $row->{'local_user'} . "', " .
        "'" . $row->{'opt_overwrite'} . "', " .
        "'" . $row->{'opt_comments'} . "', " .
        "now(), " .
        "'STARTED');"
        );
    $sth2->execute; # save import history (parameters, time when started)
    $history_id = $dbh->last_insert_id(undef, undef, qw(ihistory importid));
#    print $row->{'remote_user'}, $row->{'importid'}, $history_id, "\n";

    # TODO: import journal ($row)

    $sth2 = $dbh-> prepare (
      "update ihistory set
        istatus = 'FINISHED',
        idate = now()
        where importid = '" . $history_id . "'");
    $sth2->execute; # update import history (time when finished)
    
    $sth1 = $dbh->prepare (
      "delete from iqueue where
         local_user = '" . $row->{'local_user'} . "'"
      ); # empty all the user's request after processing last one
    $sth1->execute;

    sleep($speed_throttle); # do not hurry
    
    $sth->execute; # refresh the query
  }

  $dbh->disconnect;
  print "processed queue at ", `date`;
}
