package Perl::Critic::Policy::Variables::RequireHungarianNotation;

use strict;
use warnings;
use parent 'Perl::Critic::Policy';
use Perl::Critic::Utils ':severities';

$Perl::Critic::Policy::Variables::RequireHungarianNotation::VERSION = '0.0.2';

sub desc {
    return 'Non hungarian notation';
}

sub expl {
    return q{Use hungarian notation for variable declararions!};
}

sub supported_parameters {
    return (
        { name => 'array',     description => 'Prefix for Hash vars',                      default_string => q/a_/, },
        { name => 'hash',      description => 'Prefix for Array vars',                     default_string => q/h_/, },
        { name => 'array_ref', description => 'Prefix for Arrayref vars',                  default_string => q/ar_/, },
        { name => 'hash_ref',  description => 'Prefix for Hashref vars',                   default_string => q/hr_/, },
        { name => 'code_ref',  description => 'Prefix for Hashref vars',                   default_string => q/cr_/, },
        { name => 'object',    description => 'Prefix for Object vars',                    default_string => q/o_/, },
        { name => 'integer',   description => 'Prefix for Integer vars',                   default_string => q/i_/, },
        { name => 'string',    description => 'Prefix for String vars',                    default_string => q/s_/, },
        { name => 'boolean',   description => 'Prefix for boolean vars',                   default_string => q/b_/ },
        { name => 'regex',     description => 'Prefix for predefined regular expressions', default_string => q/rx_/ },
        { name => 'self',      description => 'Ingore self variable',                      default_string => q/self/ },
        { name => 'custom',    description => 'Custom prefixes', },
    );
}

sub default_severity {
    return $SEVERITY_LOW;
}

sub default_themes {
    return qw(cosmetic readability);
}

sub applies_to {
    return 'PPI::Statement::Variable';
}

sub violates {
    my ( $self, $o_variable, undef ) = @_;
    return if not scalar grep { $o_variable->type eq $_ } qw/my our local/;
    if ( $self->_violates_scalar($o_variable) || $self->_violates_list($o_variable) ) {
        return $self->violation( desc(), expl(), $o_variable );
    }
    return $self->violation( desc(), expl(), $o_variable ) if $self->_check_sub_variables($o_variable);
    return;
}

sub _violates_list {
    my ( $self, $o_variable ) = @_;
    my @a_childrens = $o_variable->schildren;    # "significant" children
    if ( $a_childrens[1]->isa('PPI::Token::Symbol') && $a_childrens[1]->raw_type =~ /^[@%]$/ ) {
        return 1 if !$self->_b_check_list( $a_childrens[1]->symbol, $a_childrens[1]->raw_type );
    }
    return;
}

sub _violates_scalar {
    my ( $self, $o_variable ) = @_;
    my @a_childrens = $o_variable->schildren;    # "significant" children
    if ( $a_childrens[1]->isa('PPI::Token::Symbol') && $a_childrens[1]->raw_type eq q{$} ) {
        return 1 if !$self->_b_check_scalar( $a_childrens[1]->symbol );
    }
    return;
}

sub _get_custom_prefixes {
    my ($self) = @_;
    return join q/|/, split / /, $self->{_custom};
}

sub _check_sub_variables {
    my ( $self, $o_variable ) = @_;
    return if not $o_variable->variables > 1;

    for ( map { $_->schildren } grep { $_->isa('PPI::Structure::List') } $o_variable->schildren ) {
        for ( grep { $_->isa('PPI::Token::Symbol') } $_->schildren ) {
            return 1
              if !(
                  $_->raw_type =~ /^[@%]$/
                ? $self->_b_check_list( $_->symbol, $_->raw_type )
                : $self->_b_check_scalar( $_->symbol, $_->raw_type )
              );
        }
    }
    return;
}

sub _b_check_scalar {
    my ( $self, $s_symbol, $s_raw_type ) = @_;
    return 1 if $s_symbol eq q/$/ . $self->{_self};
    for (qw/array_ref hash_ref object integer string boolean regex/) {
        return 1 if $self->_check_prefix( $s_symbol, q/$/, $_ );
    }
    if ( $self->{_custom} ) {
        my $s_custom_prefixes = $self->_get_custom_prefixes;
        return 1 if $self->_check_prefix( $s_symbol, q/$/, qq/($s_custom_prefixes)/ );
    }
    return 0;
}

sub _b_check_list {
    my ( $self, $s_symbol, $s_raw_type ) = @_;
    for (qw/array hash/) {
        return 1 if $self->_check_prefix( $s_symbol, $s_raw_type, $_ );
    }
    return 0;
}

sub _check_prefix {
    my ( $self, $s_symbol, $s_raw_type, $s_key ) = @_;
    my $s_rx_scalar = q/\\/ . $s_raw_type . ( $self->{ q/_/ . $s_key } // $s_key );
    return $s_symbol =~ /^$s_rx_scalar/ ? 1 : 0;
}

1;    # Magic true value required at end of module
__END__

=head1 NAME

Perl::Critic::Policy::Variables::RequireHungarianNotation - prohibit hungarian notation

=head1 VERSION

Version 0.0.2

=head1 SYNOPSIS

=head1 DESCRIPTION

Don't clutter your code with unnecessary variable initialization:

    my @array    = ();    # don't do this
    my %hash     = ();    # or this
    my $hashref  = {};    # or this
    my $arrayref = [];    # or this
    my $string   = '';    # or this
    
Instead, do this:

    my @a_array     = (); # do this
    my %h_hash      = (); # and this
    my $hr_hashref  = {}; # and this
    my $hr_arrayref = []; # and this
    my $s_string    = ''; # and this

=head1 SUBROUTINES/METHODS

=head2 expl()

Returns a string containing an explanation of this policy.

=head2 supported_parameters

=head2 default_severity

Returns a numeric constant defining the severity of violating this policy.

=head2 default_themes

Returns a list of strings defining the themes for this policy.

=head2 applies_to

Returns a string describing the elements to which this policy applies.

=head2 violates

Method to determine if the element currently under scrutiny violates this
policy.  If it does, return a properly constructed C<Perl::Critic::Violation>
object.  Otherwise, return C<undef>.

=head2 desc()

=head1 INTERFACE 

=for author to fill in:
    L<Perl::Critic::Policy|Perl::Critic::Policy>

=head1 DIAGNOSTICS

=for author to fill in:
    List every single error and warning message that the module can
    generate (even the ones that will "never happen"), with a full
    explanation of each problem, one or more likely causes, and any
    suggested remedies.

=over

=item C<< Error message here, perhaps with %s placeholders >>

[Description of error here]

=item C<< Another error message here >>

[Description of error here]

[Et cetera, et cetera]

=back


=head1 CONFIGURATION AND ENVIRONMENT

Perl::Critic::Policy::Variables::RequireHungarianNotation requires no configuration files or environment variables.


=head1 DEPENDENCIES

L<Perl::Critic::Policy|Perl::Critic::Policy>, L<Perl::Critic::Utils|Perl::Critic::Utils>


=head1 INCOMPATIBILITIES

None reported.

=head1 BUGS AND LIMITATIONS

Please report any bugs or feature requests to 
L<https://gitlab.com/mziescha/Perl-Critic-Policy-Variables-RequireHungarianNotation/issues>.

=head1 AUTHOR

Mario Zieschang  C<< <mziescha -at - cpan -dot- org> >>

=head1 LICENSE AND COPYRIGHT

Copyright (c) 2018, Mario Zieschang C<< <mziescha@cpan.org> >>. All rights reserved.

This module is free software; you can redistribute it and/or
modify it under the same terms as Perl itself. See L<perlartistic|perlartistic>.


=head1 DISCLAIMER OF WARRANTY

BECAUSE THIS SOFTWARE IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
FOR THE SOFTWARE, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
PROVIDE THE SOFTWARE "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER
EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE
ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE SOFTWARE IS WITH
YOU. SHOULD THE SOFTWARE PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL
NECESSARY SERVICING, REPAIR, OR CORRECTION.

IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
REDISTRIBUTE THE SOFTWARE AS PERMITTED BY THE ABOVE LICENCE, BE
LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL,
OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE
THE SOFTWARE (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING
RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A
FAILURE OF THE SOFTWARE TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF
SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
