package Gruntmaster::Page::Log;

use 5.014000;
use strict;
use warnings;
use parent qw/Exporter/;
our @EXPORT_OK = qw/generate/;
our $VERSION = '0.001';

use constant TITLE => 'Job log';

use Fcntl qw/:flock/;
use HTML::Template::Compiled;
use IO::File;
use POSIX qw/strftime/;
use YAML::Any qw/LoadFile/;
use Gruntmaster::Page qw/header footer/;

my %templates = (
  en => <<'HTML',
<table border>
<thead>
<tr><th>ID<th>Problem<th>Date<th>Size<th>User<th>Result
<tbody>
<tmpl_loop log><tr><td><a href="<tmpl_var id>"><tmpl_var id></a>
<td><a href="/pb/<tmpl_var problem>"><tmpl_var name></a>
<td><tmpl_var date>
<td><a href="<tmpl_var id>/in/<tmpl_var filename>"<tmpl_if private> data-private</tmpl_if>><tmpl_var size></a>
<td><tmpl_var user><td class="r<tmpl_var result>"><tmpl_var result_text>
</tmpl_loop>
</table>
HTML
);

$templates{$_}  = header($_, TITLE) . $templates{$_} for keys %templates;
$templates{$_} .= footer $_ for keys %templates;

sub generate{
  my $template = $templates{$_[1]};
  my $htc = HTML::Template::Compiled->new(scalarref => \$template);
  IO::File->new('>log/meta.yml')->close unless -f 'log/meta.yml';
  flock my $metafh = IO::File->new('<log/meta.yml'), LOCK_SH;
  my $meta = LoadFile 'log/meta.yml';
  my @log = sort { $b->{id} <=> $a->{id} } map {
	my $meta = LoadFile "log/$_/meta.yml";
	+{ id => $_,
	   date => strftime ('%c' => localtime $meta->{date}),
	   user => $meta->{user},
	   result => $meta->{result},
	   name => $meta->{name},
	   problem => $meta->{problem},
	   filename => $meta->{files}{prog}{name},
	   (defined $meta->{private} ? (private => $meta->{private}) : ()),
	   size => sprintf ("%.2f KiB", (-s "log/$_/in/" . $meta->{files}{prog}{name}) / 1024),
	   result_text => $meta->{result_text}} } 1 .. $meta->{last};
  $htc->param(log => \@log);
  $htc->output
}

1
