#!/usr/bin/perl

use strict;

use Time::Local;
use Date::Manip;
use Database;

my $dbh = Database->new->dbh;

my $tt9 = $dbh->selectrow_arrayref("SELECT max(time) from changes")->[0];

my ( $loncenter, $timecenter, $trainlength, $t0, $x0, $v0, $trainname ) = @ARGV;
my $ff = $dbh->selectall_arrayref(
"SELECT trklon,time,historytext,blameblock,nextids,trainid from fitfails where time=$timecenter and trklon=$loncenter order by time"
) or die "didn't get historytext?";

open F, ">>", "rtalert.log" or die "didn't open rtalert.log\n";

print F "invoked with args ", ( join " ", @ARGV ), "\n";
print F "max db time is $tt9\n";
print F "clock time is ", (time), "\n";
for (@$ff) {
    my ( undef, undef, $historytext, $blameblock, $nextids, $trainid ) = @$_;
    print F "history text follows\n";
    print F $historytext, "\n";
    my @lines = split "\n", $historytext;
    shift @lines;
    my @scores;
    for (@lines) {
        push @scores, 0 + ( split ' ', $_ )[2];
    }
    my @scores = reverse @scores;
    print F "last scores are ", ( join " ", @scores ), "\n";
    my $hit = 0;
    if ( $scores[0] > 3000 ) {
        print F "meets requirement for a single event over 3000\n";
        $hit++;
    }
    if ( $scores[0] > 800 && $scores[1] > 800 && $scores[2] > 800 ) {
        print F "meets requirement for three consecutive events over 800\n";
        $hit++;
    }
    if (   $scores[0] > 300
        && $scores[1] > 300
        && $scores[2] > 300
        && $scores[3] > 300
        && $scores[4] > 300 )
    {
        print F "meets requirement for five consecutive events over 300\n";
        $hit++;
    }
    print "hit count was $hit\n";
    print F "Would be a realtime occ alert!\n" if $hit;
    print F "\n\n";
    if ($hit) {
        $blameblock =~ s/^ST\d.//;
        $blameblock =~ s/\-\-/\-/g;
        my ( $nextid1, $nextid2 ) = split /,/, $nextids;
        open R, ">", "/home/shoppa/rocs/alarm.txt";
        print R join ",", "$loncenter-$timecenter", $blameblock,
          ( scalar localtime $timecenter ), "STOP TRAINS ON APPROACH",
          "ID $nextid1", "ID $nextid2", "IMPLEMENT SOP 15",
          "ABSOLUTE BLOCK BETWEEN PLATFORMS", "LOS Train ID $trainid";
        close R;
# 	print `/home/shoppa/rocs/cgi-bin/hornon`;
        $dbh->do( "UPDATE fitfails set wasrtalert="
              . (time)
              . " where trklon=$loncenter and time=$timecenter" );
    }
}

