package Hash::Wrap::Base;

# ABSTRACT: Hash::Wrap  base class

use 5.008009;

use strict;
use warnings;

our $VERSION = '0.01';

our $AUTOLOAD;

use Scalar::Util;

# this is called only if the method doesn't exist.
my $generate_accessor = sub {

    my ( $self, $method, $key ) = @_;

    ## no critic (ProhibitNoStrict)
    no strict 'refs';
    *{$method} = sub {
        my $self = shift;

        unless ( exists $self->{$key} ) {
            require Carp;
            Carp::croak( qq[Can't locate object method "$key" via package @{[ Scalar::Util::blessed( $self ) ]} \n] );
          }

        $self->{$key} = $_[0] if @_;

        return $self->{$key};
      };

      return *{$method}{CODE};
};

#pod =begin pod_coverage
#pod
#pod =head3 can
#pod
#pod =end pod_coverage
#pod
#pod =cut

sub can {

    my ( $self, $key ) = @_;

    my $class = Scalar::Util::blessed( $self );
    return if !defined $class;

    return unless exists $self->{$key};

    my $method = "${class}::$key";

    ## no critic (ProhibitNoStrict)
    no strict 'refs';
    return *{$method}{CODE} || $self->$generate_accessor( $method, $key );
}

sub DESTROY {}

sub AUTOLOAD {

    my $self   = $_[0];
    my $method = $AUTOLOAD;

    ( my $key = $method ) =~ s/.*:://;

    unless ( Scalar::Util::blessed( $self ) ) {
        require Carp;
        Carp::croak( qq[Can't locate class method "$key" via package @{[ ref $self]} \n] )
    }

    unless ( exists $self->{$key} ) {
        require Carp;
        Carp::croak( qq[Can't locate object method "$key" via package @{[ ref $self]} \n] )
    }

    goto &{ $self->$generate_accessor( $method, $key ) };
}


1;

__END__

=pod

=head1 NAME

Hash::Wrap::Base - Hash::Wrap  base class

=head1 VERSION

version 0.01

=begin pod_coverage

=head3 can

=end pod_coverage

=head1 BUGS AND LIMITATIONS

You can make new bug reports, and view existing ones, through the
web interface at L<https://rt.cpan.org/Public/Dist/Display.html?Name=Hash-Wrap>.

=head1 AUTHOR

Diab Jerius <djerius@cpan.org>

=head1 COPYRIGHT AND LICENSE

This software is Copyright (c) 2017 by Smithsonian Astrophysical Observatory.

This is free software, licensed under:

  The GNU General Public License, Version 3, June 2007

=cut
