package Gruntmaster::Page::Pb::Entry;

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

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

use constant FORMATS => [qw/CPP/];
use constant TITLE => '<tmpl_var name>';

my %templates = (
  en => <<'HTML',
<tmpl_var statement>

<tmpl_if cansubmit>
<h1>Submit solution</h1>
<form action="https://gm.ieval.ro/action/submit" method="POST" enctype="multipart/form-data">
<input type="hidden" name="problem" value="<tmpl_var id>">
<tmpl_if_defined contest><input type="hidden" name="contest" value="<tmpl_var contest>"></tmpl_if_defined>
<label>File: <input name="prog" required type="file"></label>

<label>File format: <select name="prog_format" required>
<tmpl_loop formats><option value="<tmpl_var _>"><tmpl_var _></option>
</tmpl_loop></select></label>

<input type="submit" value="Submit job">
</form>
</tmpl_if>
HTML
);

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

sub generate{
  my ($path, $lang) = @_;
  my $contest;
  $contest = $1 if $path =~ m,ct/([^/]*)/,;
  my $id = ($path =~ m,pb/([^/]*)/index,)[0];
  $path =~ s,/index\.html$,,;
  my $template = $templates{$_[1]};
  my $htc = HTML::Template::Compiled->new(scalarref => \$template);
  flock my $metafh = IO::File->new("<$path/meta.yml"), LOCK_SH;
  my $meta = LoadFile "$path/meta.yml";

  $htc->param(cansubmit => 1);
  if (defined $contest) {
	my $meta = LoadFile "ct/$contest/meta.yml";
	$htc->param(cansubmit => time >= $meta->{start} && time <= $meta->{end});
	$htc->param(contest => $contest);
  }
  $htc->param(formats => FORMATS);
  $htc->param(id => $id);
  $htc->param(name => $meta->{name});
  $htc->param(statement => scalar slurp "$path/statement.$lang");
  $htc->output
}

1
