package Plack::App::Gruntmaster;

use 5.014000;
use strict;
use warnings;
use parent qw/Plack::Component/;
no if $] >= 5.017011, warnings => 'experimental::smartmatch';
our $VERSION = '5999.000_001';

use File::Slurp qw/read_file/;
use HTTP::Negotiate qw/choose/;
use Plack::Request;

my %handlers;

sub call {
	my $env = $_[1];
	my $r = Plack::Request->new($env);
	my @handlers = @{ $handlers{$r->method} // [] };
	for my $handler (@handlers) {
		my ($re, $obj) = @$handler;
		my @args;
		next unless @args = $r->path =~ m/^$re$/a;
		my $format = choose $obj->variants, $r->headers;
		return $obj->generate($format, $env, map { $_ // '' } @args);
	}

	if ($r->method eq 'GET' || $r->method eq 'HEAD') {
		my $article = $r->path eq '/' ? '/index' : $r->path;
		$article = substr $article, 1;
		$article =~ tr,/,_,;
		my @variants = grep { !/\.title$/ } <a/$article.*>;
		if (@variants) {
			my $lang = choose [ map { [$_, 1, 'text/html', undef, undef, $_, undef] } map { /\.(.+)$/ } @variants ], $r->headers;
			my $content = read_file "a/$article.$lang";
			my $title = read_file "a/$article.$lang.title";
			my $html = Gruntmaster::Page::Base::header($lang, $title) . $content . Gruntmaster::Page::Base::footer($lang);
			return [200, ['Content-Type' => 'text/html', 'Content-Language' => $lang, 'Vary' => 'Accept-Language'], [$html] ]
		}
	}

	[404, ['Content-Type' => 'text/plain'], ['Not found']]
}

sub get  {
	my ($re, $obj) = @_;
	eval "require Gruntmaster::Page::$obj" or die $@;
	push @{$handlers{GET }}, [ $re, "Gruntmaster::Page::$obj" ]
}

sub post {
	my ($re, $obj) = @_;
	eval "require Gruntmaster::Page::$obj" or die $@;
	push @{$handlers{POST}}, [ $re, "Gruntmaster::Page::$obj" ]
}

BEGIN{
	my $word = qr,(\w+),a;
	my $ct = qr,(?:\/ct/$word)?,a;

	get qr,/css/$word, => 'CSS';
	get qr,/js, => 'JS';

	get qr,/ct/, => 'Ct';
	get qr,/ct/$word, => 'Ct::Entry';
	get qr,/us/, => 'Us';
	get qr,/us/$word, => 'Us::Entry';

	get qr,$ct/log/(\d+)?, => 'Log';
	get qr,$ct/log/st, => 'St';
	get qr,$ct/log/job/$word, => 'Log::Entry';
	get qr,$ct/log/src/$word\.$word, => 'Src';
	get qr,$ct/pb/, => 'Pb';
	get qr,$ct/pb/$word, => 'Pb::Entry';
	post qr,$ct/pb/$word/submit, => 'Submit';

	post qr,/action/register, => 'Register';
	post qr,/action/passwd, => 'Passwd';
}

1;
__END__
