package CatalystX::HelpText::ViewRole;
use Moose::Role;
use Try::Tiny;
use Moose::Autobox;
use namespace::autoclean;

requires 'expose_methods';

around expose_methods => sub {
    my ($orig, $self, @args) = @_;
    my $m = $self->$orig(@args) || [];
    [ $m->flatten, 'help_text' ];
};

has helptext_model => (
    is => 'ro',
    default => 'Help',
);

has comment_if_helptext_not_found => (
    is => 'ro',
    default => 1,
    isa => 'Bool',
);

sub help_text {
    my ($self, $c, $key) = @_;
    my $model = try { $c->model($self->helptext_model) };
    if (!$model) {
        $c->log->warn(sprintf("Cannot find the '%s' model for %s", $self->helptext_model, ref($self))) if $c->debug;
        return;
    }
    if (!$model->can('get_help_text_for')) {
        $c->log->warn(sprintf("Your '%s' model used by '%s' does not have a get_help_text_for method", $self->helptext_model, ref($self))) if $c->debug;
        return;
    }
    try {
        $model->get_help_text_for($key);
    }
    catch {
        $c->log->warn("Error retrieving help_text key '$key' from model: $_")
            if $c->debug;
        return '' unless $self->comment_if_helptext_not_found;
        return '<!-- Unknown help text: ' . $key . ' -->';
    };
}

1;

=head1 NAME

CatalystX::HelpText::ViewRole - Role to be applied to Views

=head1 SYNOPSIS

  package MyApp::View::HTML;
  use Moose;

  extends 'Catalyst::View::TT';
  with 'CatalystX::HelpText::ViewRole';

  ... then, in your template code ...

  [% helptext('SomeHelpTopic') %]

=head1 NOTES

Should work with any view which implements the C<expose_methods> functionality in the same manor
that L<Catalyst::View::TT> does, however this has only been tried with that view.

=head1 SEE ALSO

=over

=item L<CatalystX::HelpText>

=item L<Catalyst::View::TT/expose_methods>

=back

=head1 AUTHOR

Toomas Doran, C<< t0m at state51.co.uk >>

Cinxgler Mariaca Minda, C<< cinxgler at ci-info.com >>

=head1 COPYRIGHT

Copyright Oscar Music and Media 2011.

=head1 LICENSE

This sofware is free software, and is licensed under the same terms as perl itself.

=cut

