use strict;
use warnings;

package App::Embra::Plugin::TemplateToolkit;
$App::Embra::Plugin::TemplateToolkit::VERSION = '0.001'; # TRIAL
# ABSTRACT: use Template::Toolkit to turn file content into HTML

use Path::Class qw<>;
use Method::Signatures;
use Template;
use Moo;



has 'include_path' => (
    is => 'ro',
    default => sub { 'templates' },
    coerce => sub { Path::Class::dir( $_[0] ) },
);


has 'default_template' => (
    is => 'lazy',
    default => method { 'default'. $self->extension },
);


has 'extension' => (
    is => 'ro',
    default => sub { '.tt' },
);


has 'assembler' => (
    is => 'lazy',
);

method _build_assembler {
    Template->new({
        INCLUDE_PATH => $self->include_path,
        DEFAULT => $self->default_template,
        TRIM => 1,
    });
}

method assemble_files {
    for my $file ( @{ $self->embra->files } ) {
        next if $file->ext ne 'html';

        my $template = $file->with_ext( $self->extension );
        my $assembled;
        my $notes = {
            content => $file->content,
            name    => $file->name,
            %{ $file->notes },
        };
        use Try::Tiny;
        try {
            $self->assembler->process( $template, $notes, \$assembled ) or $self->debug( $self->assembler->error );
        } catch {
            $self->debug( $_ );
        };
        $file->content( $assembled );
        $file->notes->{assembled_by} = __PACKAGE__;
    }
}

method exclude_file( $file ) {
    return 1 if $self->include_path->subsumes( $file->name );
    return;
}

with 'App::Embra::Role::FileAssembler';
with 'App::Embra::Role::FilePruner';

1;

__END__

=pod

=encoding UTF-8

=head1 NAME

App::Embra::Plugin::TemplateToolkit - use Template::Toolkit to turn file content into HTML

=head1 VERSION

version 0.001

=head1 DESCRIPTION

This plugin will process site files through Template Toolkit. For each file with a C<.html> extension, it will look for a template in the C<include_path> with a matching name and use it to process the contents of the file into an assembled HTML document.

Templates will be passed the file's content and body as variables, as well as each of the file's notes.

=head1 ATTRIBUTES

=head2 include_path

Where to find templates. Defaults to F<templates> in the current directory. All files within the path will be pruned.

=head2 default_template

Template to use if a file doesn't have a matching template. Defaults to F<default.tt>.

=head2 extension

The extension of template files. Defaults to C<.tt>.

=head2 assembler

The object used to assemble files. Defaults to an instance of L<Template Toolkit|Template>.

=head1 AUTHOR

Daniel Holz <dgholz@gmail.com>

=head1 COPYRIGHT AND LICENSE

This software is copyright (c) 2015 by Daniel Holz.

This is free software; you can redistribute it and/or modify it under
the same terms as the Perl 5 programming language system itself.

=cut
