package Plack::App::Gruntmaster;

use 5.014000;
use strict;
our $VERSION = '5999.000_001';

use CSS::Minifier::XS;
use Encode qw/encode decode/;
use File::Slurp qw/read_file/;
use JavaScript::Minifier::XS;
use JSON::MaybeXS qw/encode_json/;
use PerlX::Maybe;
use Scope::Upper qw/unwind SUB UP/;
use Web::Simple;

use Gruntmaster::Data;
use Plack::App::Gruntmaster::HTML;

use warnings NONFATAL => 'all';
no warnings 'illegalproto';
no if $] >= 5.017011, warnings => 'experimental::smartmatch';

##################################################

use constant USER_REGEX => qr/^\w{2,20}$/a;

use constant CONTENT_TYPES => +{
	c => 'text/x-csrc',
	cpp => 'text/x-c++src',
	cs => 'text/x-csharp', # Used by GNOME. Not in mime.types.
	go => 'text/plain', # ?
	hs => 'text/x-haskell',
	java => 'text/x-java',
	pas => 'text/x-pascal',
	pl => 'text/x-perl',
	py => 'text/x-python',
};

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

use constant NOT_FOUND => [404, ['Content-Type' => 'text/plain'], ['Not found']];
use constant FORBIDDEN => [401, ['Content-Type' => 'text/plain', 'WWW-Authenticate' => 'Basic realm="Gruntmaster 6000"'], ['Forbidden']];

sub development() { ($ENV{PLACK_ENV} // 'development') eq 'development' }

my ($env, $privacy);

sub db { $env->{'gruntmaster.dbic'} }

sub remote_user {
	my $user = $env->{'gruntmaster.user'};
	$user &&= db->user($user);
	$user
}

sub admin   { remote_user && remote_user->admin }
sub contest { db->contest ($_{contest}) }
sub problem { db->problem ($_{problem}) }
sub job     { db->job     ($_{job})     }
sub user    { db->user    ($_{user})    }

sub redirect { [301, ['X-Forever' => 1, 'Location' => $_[0]], []] }
sub reply    { [200, ['Content-Type' => 'text/plain'], \@_] }
sub response {
	my ($template, $title, $params, $maxage) = @_;
	unless ($params) {
		$params = $title;
		$title = 'No title';
	}
	$params->{time} = time;
	bless {template => $template, title => $title, params => $params, maxage => ($maxage // 1)}, __PACKAGE__.'::Response'
}

sub forbid {
	my ($condition) = @_;
	$privacy = 'private' if $condition;
	return if !$condition || admin;
	unwind FORBIDDEN, SUB UP
}

sub dispatch_request{
	$env = $_[PSGI_ENV];
	$privacy = 'public';

	sub (GET) {
		sub (/css/:theme) {
			my $theme = $_{theme};
			return NOT_FOUND unless -e "css/themes/$theme.css";
			my $css = read_file "css/themes/$theme.css";
			$css .= read_file $_ for <css/*.css>;
			my @headers = ('X-Forever' => 1, 'Cache-Control' => 'public, max-age=604800', 'Content-Type' => 'text/css');
			[200, \@headers, [development ? $css : CSS::Minifier::XS::minify $css]]
		},

		sub (/js.js) {
			my $js;
			$js .= read_file $_ for <js/*.js>;
			my @headers = ('X-Forever' => 1, 'Cache-Control' => 'public, max-age=604800', 'Content-Type' => 'application/javascript');
			[200, \@headers, [development ? $js : JavaScript::Minifier::XS::minify $js]]
		},

		sub (/src/:job) {
			return NOT_FOUND if !job;
			forbid job->private || job->problem->private || job->contest && job->contest->private;
			my @headers = ('X-Forever' => 1, 'Cache-Control' => 'public, max-age=604800', 'Content-Type' => CONTENT_TYPES->{job->format});
			[200, \@headers, [job->source]]
		},

		sub (?:contest=) {
			return NOT_FOUND if !contest;
			forbid contest->is_pending;
			response_filter { return shift }
		},

		sub (?:problem=) {
			return NOT_FOUND if !problem;
			forbid problem->is_private;
			response_filter { return shift }
		},

		sub (?:format~) {
			my $format = lc ($_{format} // '');
			response_filter {
				my ($r) = @_;
				return $r if ref $r ne 'Plack::App::Gruntmaster::Response';
				my @hdrs = ('X-Forever' => 1, 'Cache-Control' => "$privacy, max-age=$r->{maxage}");
				return [200, ['Content-Type' => 'application/json', @hdrs], [encode_json $r->{params}]] if $format eq 'json';
				my $ret = render $r->{template}, 'en', title => $r->{title}, %{$r->{params}};
				[200, ['Content-Type' => 'text/html', @hdrs], [encode 'UTF-8', $ret]]
			},
		},

		sub (/st/:contest) {
			response st => 'Standings', {
				st => [ contest->standings ],
				problems => [map { $_->problem } contest->contest_problems],
			}, 10
		},

		sub (/login) {
			forbid !remote_user;

			my $return = $env->{HTTP_REFERER} // '/';
			[303, ['Set-Cookie' => "username=".remote_user->id, Location => $return], []]
		},

		sub (/ct/:contest/log/st) { redirect "/st/$_{contest}" },

		sub (/us/)                                        { response us => 'Users', {us => db->user_list} },
		sub (/ct/  + ?:owner~)                            { response ct => 'Contests', db->contest_list(%_) },
		sub (/log/ + ?:contest~&:owner~&:page~&:problem~&:private~) {
			forbid $_{private};
			response log => 'Job list', {%{db->job_list(%_)}, maybe contest => $_{contest}}
		},
		sub (/pb/  + ?:owner~&:contest~&:private~)                  {
			forbid $_{private};
			response pb => 'Problems', {%{db->problem_list(%_)}, maybe contest => $_{contest}}
		},

		sub (/us/:user)    { response us_entry => user->name, db->user_entry($_{user}) },
		sub (/ct/:contest) { response ct_entry => contest->name, db->contest_entry($_{contest}) },
		sub (/log/:job)    {
			forbid job->private;
			response log_entry => "Job  $_{job}", db->job_entry($_{job})
		},
		sub (/pb/:problem + ?contest~) {
			my (undef, undef, $contest) = @_;
			$_{contest} = $contest;
			return NOT_FOUND if !contest && !problem->is_in_archive || contest && !db->contest_problems->find($_{contest}, $_{problem});
			forbid problem->is_private;
			if (contest && contest->is_running) {
				forbid !remote_user;
				$privacy = 'private';
			}
			response pb_entry => problem->name, db->problem_entry($_{problem}, $_{contest}, remote_user && remote_user->id);
		},
		sub (/sol/:problem) {
			forbid !problem->is_in_archive;
			response sol => 'Solution of ' . problem->name, {solution => db->problem($_{problem})->solution};
		},

		sub (/) { redispatch_to '/index' },
		sub (/:article) { [200, ['Content-Type' => 'text/html', 'Cache-Control' => 'public, max-age=60', 'X-Forever' => 1], [render_article $_{article}, 'en']] }
	},

	sub (POST) {
		sub (/action/register + %:username=&:password=&:confirm_password=&:name=&:email=&:phone=&:town=&:university=&:level=) {
			return reply 'Parameter too long' if grep { length > 200 } values %_;
			return reply 'Bad username. Allowed characters are letters, digits and underscores, and the username must be between 2 and 20 characters long.' unless $_{username} =~ USER_REGEX;
			return reply 'Username already in use' if db->user($_{username});
			return reply 'The two passwords do not match' unless $_{password} eq $_{confirm_password};

			db->users->create({id => $_{username}, name => $_{name}, email => $_{email}, phone => $_{phone}, town => $_{town}, university => $_{university}, level => $_{level}});
			db->user($_{username})->set_passphrase($_{password});

			purge '/us/';
			reply 'Registered successfully';
		},

		sub (/action/passwd + %:password=&:new_password=&:confirm_new_password=) {
			forbid !remote_user;
			return reply 'Incorrect password' unless remote_user->check_passphrase($_{password});
			return reply 'The two passwords do not match' unless $_{new_password} eq $_{confirm_new_password};
			remote_user->set_passphrase($_{new_password});
			reply 'Password changed successfully';
		},

		sub (/action/submit + %:problem=&:contest~&:prog_format=&:source_code~ + *prog~) {
			my (undef, undef, $prog) = @_;
			forbid !remote_user;
			return reply 'This contest has finished' if contest && contest->is_finished;
			return reply 'This contest has not yet started' if !admin && contest && contest->is_pending;
			return reply 'Maximum source size is 10KB' if ($prog ? $prog->size : length $_{source_code}) > 10 * 1024;
			return reply 'You must wait 30 seconds between jobs' if !admin && time <= remote_user->lastjob + 30;
			remote_user->update({lastjob => time});

			my $source = $prog ? read_file $prog->path : $_{source_code};
			unlink $prog->path if $prog;
			my $newjob = db->jobs->create({
				maybe contest => $_{contest},
				maybe private => problem->private,
				date => time,
				extension => FORMAT_EXTENSION->{$_{prog_format}},
				format => $_{prog_format},
				problem => $_{problem},
				source => $source,
				owner => remote_user->id,
			});

			purge '/log/';
			[303, [Location => '/log/' . $newjob->id], []]
		}
	}
}


1;
__END__
