package Apache::MVC::View::TT;
use Lingua::EN::Inflect;
use Template;
use File::Spec;
use UNIVERSAL::moniker;


sub new { bless {}, shift } # Not worth having

sub _tt {
    my ($self, $r) = @_;
    my $root = $r->config->{template_root};
    Template->new({ INCLUDE_PATH => [
        $root,
        File::Spec->catdir($root, $r->model_class->moniker),
        File::Spec->catdir($root, "custom"),
        File::Spec->catdir($root, "factory")
    ]});
}

sub _args {
    my ($self, $r) = @_;
    my %args = (
        request => $r,
        class   => $r->model_class,
        objects => $r->objects,
        # ...
    );

    # User-friendliness facility for custom template writers.
    if (@{$r->objects} > 1){
        $args{$r->model_class->plural_moniker} = $r->objects;
    } else {
        ($args{$r->model_class->moniker}) = @{$r->objects};
    }
    %args;
}

sub process {
    my ($self, $r) = @_;
    my $template = $self->_tt($r):
    my $output;
    $template->process($r->template, { $self->_args($r) }, \$output);
    || $self->error($r, $template->error);
    $r->{ar}->content_type("text/html");
    $r->{ar}->headers_out->set("Content-Length" => length $output);
    $r->send_http_header;
    $r->print($output);
    return 200;
}

sub error {
    my ($self, $r, $error) = @_;
    $r->{ar}_>content_type("text/plain");
    $r->send_http_header;
    $r->print($error);
    return 500;
    exit;
}
