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 HTML::Template::Compiled;
use List::Util qw/sum/;
use POSIX qw/strftime/;
use Gruntmaster::Page::Common qw/header footer/;
use Gruntmaster::Data qw/problems jobcard job_result_text job_result job_problem job_user/;

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{
	local $Gruntmaster::Data::contest = ($_[0] =~ m,^ct/([^/]+)/,)[0];
	my $htc = HTML::Template::Compiled->new(scalarref => \$templates{$_[1]});

	my @problems = sort problems;
	my %scores;
	for (1 .. jobcard) {
		if (job_result_text =~ m/^(\d+)/) {
			$scores{job_user()}{job_problem()} = $1;
		} else {
			$scores{job_user()}{job_problem()} = job_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
