#!/usr/bin/env perl

use strict;
use warnings;
use vars qw( $VERSION );
$VERSION = '0.01';

use Config::YAML;
use HTML::TreeBuilder;
use HTTP::Request;
use LWP::UserAgent;
use LWP::ConnCache;
use DateTime::Format::Strptime;
use DBI;

#use Getopt::Long qw( GetOptions :config auto_help auto_version );
use Pod::Usage qw( pod2usage );
# accept no options
pod2usage( -msg => "Unknown option: @ARGV", -exitval => 2 ) if @ARGV;

my $filter_records = 0;

my $rcfile = "$ENV{HOME}/.arclogrc";
$rcfile = File::Spec->canonpath($rcfile);

my $c = read_rcfile($rcfile);
my $logdb = $c->get_logdb;
die "no log file configured" unless $logdb;
my $dbh = DBI->connect("dbi:SQLite:dbname=$logdb","","");
die "can not open logdb" unless $dbh;

my $query = $dbh->prepare("SELECT record, stamp FROM log")
    or die "database error: $!";
$query->execute or die "database error: $!";
my $rows = $query->fetchall_arrayref(undef);

#$records = [ $records->[-1] ];

my @myfilters;
foreach my $filter (@{$c->get_event_filters}) {
    push @myfilters, qr/$filter/;
}

my $strptime = DateTime::Format::Strptime->new(
    pattern => '%Y-%m-%dT%H:%M:%S'
);

# unpack records
my @records;
foreach my $row (@$rows) {
    my %rec;
    @rec{qw( host time device event elapse_time errors )} 
        = split(/\|/, $row->[0]);
    $rec{stamp} = $row->[1];
    $rec{time} = $strptime->parse_datetime($rec{time});
    push @records, \%rec;
}

# sort by time
@records = sort { $a->{time} cmp $b->{time} } @records;

RECORDS: foreach my $rec (@records) {
    my ($host, $stamp, $time, $device, $event, $elapse_time, $errors)
        = @$rec{qw( host stamp time device event elapse_time errors )};

    # do not print filtered records
    if ($filter_records) {
        foreach my $filter (@myfilters) {
            next RECORDS if $event =~ /$filter/;
        }
    }

    no warnings qw( uninitialized );
    print "$stamp - $host $time $device $event $elapse_time $errors\n";
    use warnings;
}

sub read_rcfile
{
    my $rcfile = shift;

    return unless defined $rcfile;

    if (!-f $rcfile) {
        open(my $fh, '>', $rcfile) or die "can't open file: $!";
        close($fh) or die "can't close file:$!";
    }

    return Config::YAML->new(
            config => $rcfile,
            output => $rcfile,
    );
}
