package Plack::App::Gruntmaster::HTML;
use v5.14;
use parent qw/Exporter/;
our @EXPORT = qw/render render_article/;

use File::Slurp qw/read_file/;
use HTML::Seamstress;
use POSIX qw//;
use Data::Dumper qw/Dumper/;

sub ftime ($)   { POSIX::strftime '%c', localtime shift }
sub literal ($) { HTML::Element::Library::super_literal shift // '' }

sub HTML::Element::edit_href {
	my ($self, $sub) = @_;
	local $_ = $self->attr('href');
	$sub->();
	$self->attr(href => $_);
}

sub HTML::Element::iter3 {
	my ($self, $data, $code) = @_;
	my $orig = $self;
	my $prev = $orig;
	for my $el (@$data) {
		my $current = $orig->clone;
		$code->($el, $current);
		$prev->postinsert($current);
		$prev = $current;
	}
	$orig->detach;
}

sub HTML::Element::fid    { shift->look_down(id    => shift) }
sub HTML::Element::fclass { shift->look_down(class => shift) }

sub HTML::Element::namedlink {
	my ($self, $id, $name) = @_;
	$name = $id unless $name =~ /[[:graph:]]/;
	$self = $self->find('a');
	$self->edit_href(sub {s/id/$id/});
	$self->replace_content($name);
}

sub render {
	my ($tmpl, $lang, %args) = @_;
	$lang //= 'en';
	my $meat = _render($tmpl, $lang, %args);
	_render('skel', $lang, %args, meat => $meat)
}

sub render_article {
	my ($art, $lang) = @_;
	$lang //= 'en';
	my $title = read_file "a/$art.$lang.title";
	my $meat  = read_file "a/$art.$lang";
	_render('skel', $lang, title => $title , meat => $meat)
}

sub _render {
	my ($tmpl, $lang, %args) = @_;
	my $builder = HTML::Seamstress->new;
	$builder->ignore_unknown(0);
	my $tree = $builder->parse_file("tmpl/$tmpl.$lang");
	$tree = $tree->guts unless $tmpl eq 'skel';
	$tree->defmap(smap => \%args);
	my $process = __PACKAGE__->can("process_$tmpl");
	$process->($tree, %args) if $process;
	$tree->as_HTML;
}

sub process_skel {
	my ($tree, %args) = @_;
	$tree->content_handler(
		title   =>         $args{title},
		content => literal $args{meat});
}

sub process_us_entry {
	my ($tree, %args) = @_;
	$tree->fid($_)->attr('href', "/$_/?owner=$args{id}") for qw/log pb/;
	$tree->fid('track_user')->attr('data-user', $args{id});
	my @solved = map { $_->{solved} ? ($_->{problem}) : () } @{$args{problems}};
	my @attempted = map { !$_->{solved} ? ($_->{problem}) : () } @{$args{problems}};

	my $pbiter = sub {
		my ($data, $li) = @_;
		$li->find('a')->namedlink($data);
	};
	$tree->fid('solved')->find('li')->iter3(\@solved, $pbiter);
	$tree->fid('attempted')->find('li')->iter3(\@attempted, $pbiter);
	$tree->fid('solved_count')->replace_content(scalar @solved);
	$tree->fid('attempted_count')->replace_content(scalar @attempted);

	my $ctiter = sub {
		my ($data, $td) = @_;
		$td->fclass('contest')->namedlink($data->{contest}, $data->{contest_name});
		$td->fclass('score')->replace_content($data->{score});
		$td->fclass('rank')->replace_content($data->{rank});
	};
	$tree->find('table')->find('tbody')->find('tr')->iter3($args{contests}, $ctiter);
}

sub process_us {
	my ($tree, %args) = @_;
	my $iter = sub {
		my ($data, $tr) = @_;
		$tr->fclass('user')->namedlink($data->{id}, $data->{name});
		$tr->fclass($_)->replace_content($data->{$_}) for qw/solved attempted contests/;
	};
	$tree->find('tbody')->find('tr')->iter3($args{us}, $iter);
}

sub process_ct_entry {
	my ($tree, %args) = @_;
	$_->edit_href (sub {s/contest_id/$args{id}/}) for $tree->find('a');
	$tree->fid('links')->detach unless $args{started};
	$tree->content_handler(
		start       => ftime   $args{start},
		stop        => ftime   $args{stop},
		description => literal $args{description});
}

sub process_ct {
	my ($tree, %args) = @_;
	my $iter = sub {
		my ($data, $tr) = @_;
		$data->{$_} = ftime $data->{$_} for qw/start stop/;
		$tr->hashmap(class => $data, [qw/name owner/]);
		$tr->fclass('name')->namedlink($data->{id}, $data->{name});
		$tr->fclass('owner')->namedlink($data->{owner}, $data->{owner_name});
	};
	$args{$_} ? $tree->fid($_)->find('tbody')->find('tr')->iter3($args{$_}, $iter) : $tree->fid($_)->detach for qw/running pending finished/;
}

sub process_pb_entry {
	my ($tree, %args) = @_;
	$tree->fid('owner')->edit_href(sub{s/owner_id/$args{owner}/});
	$tree->fid('job_log')->edit_href(sub{s/problem_id/$args{id}/});
	$tree->fid('solution')->edit_href(sub{s/problem_id/$args{id}/});
	$tree->content_handler(
		statement => literal $args{statement},
		author    =>         $args{author},
		owner     =>         $args{owner_name} || $args{owner});
	if ($args{contest_stop}) {
		$tree->fid('solution')->detach;
		$tree->fid('solution_modal')->detach;
		my $countdown = $tree->fid('countdown');
		$countdown->attr('data-start' => $args{contest_start});
		$countdown->attr('data-stop' => $args{contest_stop});
		$countdown->attr('data-time' => $args{time});
		my $left = $args{contest_stop} - $args{time};
		$countdown->replace_content(sprintf '%02d:%02d:%02d', $left/60/60, $left/60%60, $left%60);
		$tree->fid('score')->attr('data-value' => $args{value});
		$tree->fid('score')->replace_content(Gruntmaster::Data::calc_score($args{value}, $args{time} - $args{contest_start}, 0, $args{contest_stop} - $args{contest_start}));
	} else {
		$_->detach for $tree->fclass('rc'); # requires contest
		$tree->fid('solution_modal')->fclass('modal-body')->replace_content(literal $args{solution});
	}
	$tree->fid('solution')->detach unless $args{solution};
	if ($args{cansubmit}) {
		$tree->look_down(name => 'problem')->attr(value => $args{id});
		my $contest = $tree->look_down(name => 'contest');
		$contest->attr(value => $args{contest}) if $args{contest};
		$contest->detach unless $args{contest}
	} else {
		$tree->fid('submit')->detach
	}
}

sub process_sol {
	my ($tree, %args) = @_;
	$tree->content_handler(solution => literal $args{solution});
}

sub process_pb {
	my ($tree, %args) = @_;
	my $titer = sub {
		my ($data, $tr) = @_;
		$tr->set_child_content(class => 'author', $data->{author});
		$tr->fclass('name')->namedlink($data->{id}, $data->{name});
		$tr->fclass('name')->find('a')->edit_href(sub {$_ .= "?contest=$args{contest}"}) if $args{contest};
		$tr->fclass('owner')->namedlink($data->{owner}, $data->{owner_name});
	};
	my $iter = sub {
		my ($data, $div) = @_;
		$div->attr(id => $data);
		$div->find('h2')->replace_content(ucfirst $data);
		$div->find('tbody')->iter3($args{$data}, $titer);
	};
	$tree->fid('beginner')->iter3([grep {$args{$_}} qw/beginner easy medium hard/], $iter);
}

sub process_log_entry {
	my ($tree, %args) = @_;
	$tree->fid('problem')->namedlink(@args{qw/problem problem_name/});
	$tree->fid('owner')->namedlink(@args{qw/owner owner_name/});
	$tree->fid('source')->namedlink("$args{id}.$args{extension}", sprintf '%.2fKB', $args{size}/1024);
	if ($args{contest}) {
		$tree->fid('contest')->namedlink(@args{qw/contest contest_name/});
		$tree->fid('problem')->find('a')->edit_href(sub {$_.="?contest=$args{contest}"});
	} else {
		$tree->fid('contest')->left->detach;
		$tree->fid('contest')->detach;
	}

	$args{errors} ? $tree->fid('errors')->find('pre')->replace_content($args{errors}) : $tree->fid('errors')->detach;
	my $iter = sub {
		my ($data, $tr) = @_;
		$data->{time} = sprintf '%.4fs', $data->{time};
		$tr->defmap(class => $data);
		$tr->fclass('result_text')->attr(class => "r$data->{result}")
	};
	$args{results} ? $tree->fid('results')->find('tbody')->find('tr')->iter3($args{results}, $iter) : $tree->fid('results')->detach;
}

sub process_log {
	my ($tree, %args) = @_;
	my $iter = sub {
		my ($data, $tr) = @_;
		$tr->fclass('id')->namedlink($data->{id});
		$tr->fclass('problem')->namedlink($data->{problem}, $data->{problem_name});
		$tr->fclass('problem')->find('a')->edit_href(sub{$_ .= "?contest=$args{contest}"}) if $args{contest};
		$tr->fclass('date')->replace_content(ftime $data->{date});
		$tr->fclass('size')->namedlink("$data->{id}.$data->{extension}", sprintf "%.2fKB", $data->{size}/1024);
		$tr->fclass('size')->attr('data-private', '') if $data->{private};
		$tr->fclass('owner')->namedlink($data->{owner}, $data->{owner_name});
		$tr->fclass('result_text')->replace_content($data->{result_text});
		$tr->fclass('result_text')->attr(class => "r$data->{result}");
	};
	$tree->find('table')->find('tbody')->find('tr')->iter3($args{log}, $iter);
	$args{next_page} ? $tree->fclass('next')->namedlink($args{next_page}, 'Next') : $tree->fclass('next')->detach;
	$args{previous_page} ? $tree->fclass('previous')->namedlink($args{previous_page}, 'Previous') : $tree->fclass('previous')->detach;
	$tree->fclass('current')->replace_content("Page $args{current_page} of $args{last_page}");
}

sub process_st {
	my ($tree, %args) = @_;
	$args{problems} //= [];
	my $pbiter = sub {
		my ($data, $th) = @_;
		$th->attr(class => undef);
		$th->namedlink($data->id, $data->name);
	};
	$tree->fclass('problem')->iter3($args{problems}, $pbiter);
	my $iter = sub {
		my ($st, $tr) = @_;
		$tr->set_child_content(class => 'rank', $st->{rank});
		$tr->set_child_content(class => 'score', $st->{score});
		$tr->fclass('user')->namedlink($st->{user}, $st->{user_name});
		my $pbscore = $tr->fclass('pbscore');
		$pbscore->iter($pbscore => @{$st->{scores}});
	};
	$tree->find('tbody')->find('tr')->iter3($args{st}, $iter);
}
