use v5.24;

package Dist::Zilla::Plugin::LocalHTML::Pod2HTML;
# ABSTRACT: Pod::Simple::HTML wrapper to generate local links for project modules.

our $VERSION = 'v0.1.0';

use File::Spec;
use Data::Dumper;
use Cwd;

use Moose;
use MooseX::NonMoose;
use namespace::autoclean;
extends qw<Pod::Simple::HTML>;

has callerPlugin => (
    is      => 'ro',
    isa     => 'Dist::Zilla::Plugin::LocalHTML',
    handles => [qw<log log_debug>],
);

has prefixRx => (
    is      => 'ro',
    lazy    => 1,
    builder => 'init_prefixRx',
);

around do_pod_link => sub {
    my $orig   = shift;
    my $this   = shift;
    my ($link) = @_;

    $this->log_debug( "do_pod_link:", Dumper($link) );

    if ( $link->tagname eq 'L' and $link->attr('type') eq 'pod' ) {
        my $lpRx = $this->prefixRx;
        my $to   = "" . $link->attr('to');
        if ( $to =~ /^$lpRx/n ) {
            my $toFile = File::Spec->catfile(split /::/, $to);
            my $ref = $this->callerPlugin->base_filename($toFile);
            $this->log_debug("Resulting link:", $ref);
            return $ref;
        }
    }
};

sub init_prefixRx {
    my $this = shift;
    return
      "(?<prefix>" . join( "|", @{ $this->callerPlugin->local_prefix } ) . ")";
}

1;

__END__

=pod

=encoding UTF-8

=head1 NAME

Dist::Zilla::Plugin::LocalHTML::Pod2HTML - Pod::Simple::HTML wrapper to generate local links for project modules.

=head1 VERSION

version v0.1.0

=head1 ATTRIBUTES

=head2 C<callerPlugin>

Points back to the parent plugin object.

=head2 prefixRx

Contains regexp for matching local modules.

=head1 METHODS

=head2 C<do_pod_link>

Inherited from L<Pod::Simple::HTML>

=head2 C<init_prefixRx>

Builder for C<prefixRx> attribute. Generates regexp from caller plugin
C<local_prefix> attribute.

=head1 AUTHOR

Vadim Belman <vrurg@cpan.org>

=head1 COPYRIGHT AND LICENSE

This software is copyright (c) 2017 by Vadim Belman.

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
