#!/usr/bin/perl
#use strict;
#use warnings;

use CGI;
use File::Find;
use Time::HiRes qw/ gettimeofday tv_interval /;

our %test_data;

do 'test-data' or die "Can't load test data: $!\n";

my %results;

my $start_run = [gettimeofday];

# sorry, but i'm not very patient

my %skip_list = ( gray =>     qr/^(constitution|(un)?random.*)$/,
                  varga =>    qr/^(constitution|(un)?random.*)$/,
                  baringer => qr/^unrandom3$/);

sub test_it {
    return unless $_ =~ /^.*\.pm$/;
    $_ =~ s/\.pm$//;
    my $name = $_;
    print "Testing $name\n";
    do "$name.pm";
    my $i = 0;
    my $ok = 0;
    local $| = 1;
    foreach my $test (keys %test_data) {
        if ($skip_list{$name} && $test =~ $skip_list{$name}) {
            $results{$name}->{$test} = { ok => "blue", time => "skip" };
            next;
        }
        print "$test: ";
        $results{$name}->{$test} = { ok => "red", time => -1 };
        my $start = [gettimeofday];
        my $got = repeated_substring($test_data{$test}->{input});
        my $end = [gettimeofday];
        $results{$name}->{$test}->{time} = sprintf "%.5f", tv_interval($start, $end);
        my $output = $test_data{$test}->{output};
        if (ref $output eq 'ARRAY') {
            foreach my $o (@{ $output }) {
                $results{$name}->{$test}->{ok} = "green" if $o eq $got;
            }
        } else {
            $results{$name}->{$test}->{ok} = "green" if $output eq $got;
        }
        print "not " unless $results{$name}->{$test}->{ok} eq "green";
        print "ok in ", $results{$name}->{$test}->{time}, " seconds\n";
    }
}

find(\&test_it, '.');

open RESULTS, ">results.html" or die "Can't open results.html: $!";

print RESULTS "<html><body><h2>Results:</h2>\n";

print RESULTS "<div font=\"-2\"><table>\n";

print RESULTS "<tr><td>&nbsp;</td>\n";

foreach my $name (sort { $a cmp $b } keys %results ) {
    print RESULTS "<td>$name</td>\n";
}
print RESULTS "</tr>\n";

foreach my $test (sort { $a cmp $b } keys %test_data) {
    print RESULTS "<tr><td>$test</td>\n";
    foreach my $name (sort { $a cmp $b } keys %results) {
        my $color = $results{$name}->{$test}->{ok};
        print RESULTS "<td bgcolor=\"$color\">", $results{$name}->{$test}->{time}, "</td>\n";
    }
    print RESULTS "</tr>\n";
}

print RESULTS "</table></div><h2>Test Summary:</h2>\n";

foreach my $test (keys %test_data) {
    print RESULTS "<h3>$test</h3>\n";
    print RESULTS "Input:<br/>\n";
    print RESULTS "<pre>'", $test_data{$test}->{input}, "'</pre>";
    print RESULTS "Expected Output:\n";
    my $out = $test_data{$test}->{output};
    if (length $out > 1000) {
        $out = substr($out, 0, 1000) . "...";
    }
    if (ref $out eq 'ARRAY') {
        print RESULTS join "or", map { "<pre>'$_'</pre>" } @{ $out };
    } else {
        print RESULTS "<pre>'$out'</pre>";
    }
}

print RESULTS "</body></html>\n";

close RESULTS;
