package Gruntmaster::Handlers;

use 5.014000;
use strict;
use warnings;
our $VERSION = '0.001';

use Apache2::Access;
use Apache2::Authen::Passphrase qw/pwcheck pwset USER_REGEX/;
use Apache2::AuthzCaps qw/hascaps/;
use Apache2::RequestRec;
use Apache2::RequestIO;
use Apache2::Request;
use Apache2::Const qw/OK DECLINED/;
use Apache2::Log;
use Apache2::Upload;

use Cwd qw/cwd/;
use File::Basename qw/fileparse/;
use File::Temp qw/tempdir/;
use File::Copy qw/move/;
use Gruntmaster::Data;

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

sub aputs{
	my ($r, $str) = @_;
	$r->set_content_length(length $str);
	$r->puts($str);
	$r->content_type('text/plain');
	OK
}

sub submit{
  my $r = shift;
  my $req = Apache2::Request->new($r);
  my ($problem, $format, $contest, $private, $prog) = map {scalar $req->param($_)} 'problem', 'prog_format', 'contest', 'private', 'source_code';
  my $upload = $req->upload('prog');
  if (defined $upload) {
	  my $temp;
	  $upload->slurp($temp);
	  $prog = $temp if $temp
  }
  die if defined $contest && $contest !~ /^\w+$/ ;
  die if defined $contest && (time < contest_start $contest || time > contest_end $contest);
  return aputs 'A required parameter was not supplied' if grep { !defined } $problem, $format, $prog;

  local $Gruntmaster::Data::contest = $contest;

  my $job = push_job (
	  date => time,
	  problem => $problem,
	  user => $r->user,
	  defined $private ? (private => $private) : (),
	  defined $contest ? (contest => $contest, private => 1) : (),
	  filesize => length $prog,
	  extension => FORMAT_EXTENSION->{$format},
  );

  set_job_inmeta $job, {
	  files => {
		  prog => {
			  format => $format,
			  name => 'prog.' . FORMAT_EXTENSION->{$format},
			  content => $prog,
		  }
	  }
  };

  $contest //= '';
  PUBLISH 'jobs', "$contest.$job";
  $r->print("Job submitted");
  OK
}

sub register{
	my $r = shift;
	my $req = Apache2::Request->new($r);
	my ($username, $password, $confirm_password, $name, $email, $phone, $town, $university, $level) = map { die if length > 200; $_ } map {scalar $req->param($_)} qw/username password confirm_password name email phone town university level/;

	local $Apache2::Authen::Passphrase::rootdir = $r->dir_config('AuthenPassphraseRootdir');
	return aputs $r, '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 aputs $r, 'Username already in use' if -e "$Apache2::Authen::Passphrase::rootdir/$username.yml";
	return aputs $r, 'The two passwords do not match' unless $password eq $confirm_password;
	return aputs $r, 'All fields are required' if grep { !length } $username, $password, $confirm_password, $name, $email, $phone, $town, $university, $level;
	pwset $username, $password;

	insert_user $username, name => $name, email => $email, phone => $phone, town => $town, university => $university, level => $level;

	PUBLISH genpage =>  "us/index.html";
	PUBLISH genpage =>  "us/$username.html";
	aputs $r, 'Registered successfully';
}

sub passwd{
	my $r = shift;
	my $req = Apache2::Request->new($r);
	my ($oldpass, $newpass, $confirm) = map {scalar $req->param($_)} 'password', 'new_password', 'confirm_new_password';

	local $Apache2::Authen::Passphrase::rootdir = $r->dir_config('AuthenPassphraseRootdir');
	return aputs $r, 'Incorrect password' unless eval { pwcheck $r->user, $oldpass; 1 };
	return aputs $r, 'The two passwords do not match' unless $newpass eq $confirm;

	pwset $r->user, $newpass;
	aputs $r, 'Password changed successfully';
}

sub problem_mark_open{
	my $r = shift;
	$r->uri =~ m,/ct/([^/]*)/pb/([^.]*),;
	$r->log_error("Marking open for contest $1 problem $2 and user " . $r->user);
	local $Gruntmaster::Data::contest = $1;
	my $problem = $2;
	mark_open $problem, $r->user;
}

=begin comment

sub private{
  my $r = shift;
  my $dir = (fileparse $r->uri)[1];
  my $user = $r->user;
  chdir $r->dir_config('root') . $dir;

  for my $requirement (map { $_->{requirement} } @{$r->requires}) {
	my ($command, @args) = split ' ', $requirement;

	given ($command){
	  when('admin-if-private'){
		my $meta = LoadFile 'meta.yml';
		return OK if !$meta->{private} || ($r->user && hascaps $r->user, 'gmadm')
	  }

	}
  }

  DECLINED
}

=end comment

=cut

1;
__END__
# Below is stub documentation for your module. You'd better edit it!

=head1 NAME

Gruntmaster::Handlers - Perl extension for blah blah blah

=head1 SYNOPSIS

  use Gruntmaster::Handlers;
  blah blah blah

=head1 DESCRIPTION

Stub documentation for Gruntmaster::Handlers, created by h2xs. It looks like the
author of the extension was negligent enough to leave the stub
unedited.

Blah blah blah.


=head1 SEE ALSO

Mention other useful documentation such as the documentation of
related modules or operating system documentation (such as man pages
in UNIX), or any relevant external documentation such as RFCs or
standards.

If you have a mailing list set up for your module, mention it here.

If you have a web site set up for your module, mention it here.

=head1 AUTHOR

Marius Gavrilescu, E<lt>marius@E<gt>

=head1 COPYRIGHT AND LICENSE

Copyright (C) 2013 by Marius Gavrilescu

This library is free software; you can redistribute it and/or modify
it under the same terms as Perl itself, either Perl version 5.18.1 or,
at your option, any later version of Perl 5 you may have available.


=cut
