package Text::Wigwam::Stash::Magic::Base;

use strict;
use warnings;
no warnings q/uninitialized/;

our $VERSION = '0.01';

use Scalar::Util qw( blessed reftype );

sub new {
    my ($class, @args) = @_;
    return bless {}, ref($class) || $class;
}

sub conjure {
    my ($self, $val, $key, $ref) = @_;
    my $class = ref($self) || $self;

    my $ckey = ucfirst lc $key;

    my $type
      = blessed($val) && $val->isa( q/Text::Wigwam::Expression/ )
        ? 'Expr'
        : reftype($val) || 'String'
    ;

    my $subclass = join( "::" => $class, ucfirst lc $type );

     # Plain reference
    return $subclass->$ckey($val, $key, $ref)
      if(
          !blessed $val
          || (
                  blessed $val
               && $val->isa( q/Text::Wigwam::Expression/ )
             )
      )
    ;
     # Object method exists?
    return _condense( $val->$key ) if $val->can($key);
     # Pseudo method exists?
    return $subclass->$ckey($val, $key, $ref) if $subclass->can($ckey);
     # Object has AUTOLOAD handler?
    return _condense( $val->$key ) if $val->can( q/AUTOLOAD/ );
     # Default
    return $subclass->$ckey($val, $key, $ref);
}

sub _condense {
    return [@_] if scalar @_ > 1;
    return $_[0];
}

