package Gruntmaster::Page::St;

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

use constant TITLE => 'Standings';

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

my %templates = (
  en => <<'HTML',
<table border>
<thead>
<tr><th>Username<tmpl_loop problems><th><tmpl_var _></tmpl_loop><th>Total
<tbody>
<tmpl_loop st><tr><td><tmpl_var user>
<tmpl_loop scores><td><tmpl_var _>
</tmpl_loop><td><tmpl_var score>
</tmpl_loop>
</table>
HTML
);

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

sub generate{
  my ($path, $lang) = @_;
  $path =~ s,/st\.html$,,;
  my $template = $templates{$lang};
  my $htc = HTML::Template::Compiled->new(scalarref => \$template);
  IO::File->new(">$path/meta.yml")->close unless -f "$path/meta.yml";
  flock my $metafh = IO::File->new("<$path/meta.yml"), LOCK_SH;
  my $meta = LoadFile "$path/meta.yml";
  my @problems = sort grep { /^\w+$/ } map { s,.*/,,r } <$path/../pb/*>;
  my %scores;
  for (1 .. $meta->{last}) {
	my $meta = LoadFile "$path/$_/meta.yml";
	if ($meta->{result_text} =~ m/^(\d+)/) {
	  $scores{$meta->{user}}{$meta->{problem}} = $1;
	} else {
	  $scores{$meta->{user}}{$meta->{problem}} = $meta->{result} ? 0 : 100;
	}
  }

  my @st = sort { $b->{score} <=> $a->{score} } map {
	my $user = $_;
	+{
	  user => $user,
	  score => sum (values $scores{$user}),
	  scores => [map { $scores{$user}{$_} // '-'} @problems],
	}
  } keys %scores;
  $htc->param(problems => \@problems);
  $htc->param(st => \@st);
  $htc->output
}

1
