package Gruntmaster::Page::Submit;

use Gruntmaster::Page::Base;

use constant FORMAT_EXTENSION => {
	C => 'c',
	CPP => 'cpp',
	MONO => 'cs',
	JAVA => 'java',
	PASCAL => 'pas',
	PERL => 'pl',
	PYTHON => 'py',
};

sub generate{
	my ($self, $frm, $env) = @_;
	my $r = Plack::Request->new($env);
	my ($problem, $format, $contest, $private, $prog) = map {scalar $r->param($_)} 'problem', 'prog_format', 'contest', 'private', 'source_code';
	$problem //= $env->{'gruntmaster.problem'};
	$contest //= $env->{'gruntmaster.contest'};
	my $upload = $r->upload('prog');
	if (defined $upload) {
		my $temp = read_file $upload->path;
		$prog = $temp if $temp
	}
	die if defined $contest && $contest !~ /^\w+$/ ;
	die if defined $contest && (time > db($env)->contest($contest)->stop);
	return reply 'A required parameter was not supplied' if grep { !defined } $problem, $format, $prog;
	return reply 'Maximum source size is 10KB' if length $prog > 25 * 1024;
	return reply 'You must wait 30 seconds between jobs' unless time > db($env)->user($r->user)->lastjob + 30;
	db($env)->user($r->user)->update({lastjob => time});

	db($env)->jobs->create({
		defined $contest ? (contest => $contest) : (),
		date => time,
		extension => FORMAT_EXTENSION->{$format},
		format => $format,
		defined $private ? (private => $private) : (),
		problem => $problem,
		source => $prog,
		owner => $r->user
	});

	$contest //= '';
	#PUBLISH 'jobs', "$contest.$job";
	[303, [Location => $r->path =~ s,/pb/\w+/submit$,/log/,r], ['']]
}

1
