# THIS IS A WORK IN PROGRESS
# IT SHOULD BE CONSIDERED ALPHA
# BUT I EXPECT IT TO IMPROVE
# THIS IS A RE-IMPLEMENTATION OF PREVIOUS CODE THAT WAS WRITTEN
# ON-THE-FLY AS NEEDED. 

# YOU ARE ADVISED TO RUN THE TEST SCRIPT!!!


package Debug::Xray::WatchScalar;
use strict;
use warnings;

use strict;
use Exporter qw(import);

our $VERSION     = 0.03;
our @ISA         = qw(Exporter);
our @EXPORT_OK   = qw( set_log_handler TIESCALAR STORE FETCH); # TODO SEE WHAT WE NEED HERE

use Carp::Assert;
use Data::Dumper;

use parent 'Tie::Scalar';


my $LogHandler;


sub TIESCALAR {
    assert ( (($#_==1) or ($#_==2)), 'Parms' );

    my $class = shift;
    assert( $class eq 'Debug::Xray::WatchScalar' );

    my $var_name = shift;
    assert ($var_name, 'Must have variable name');
    assert ($var_name =~ /^\$/, 'Variable name must be have sigil: found ' . $var_name);

    my $value = shift || undef;

    my $self  = {};

    $self->{VAR_NAME} = $var_name;
    $self->{VALUE} = $value;

    $value = 'undef' unless defined $value;
    $LogHandler->("TIE: TIESCALAR $var_name=$value");
    return bless $self, $class;
}


sub STORE {    
    assert ( $#_==1, "Parms: found " . Dumper \@_ );
    assert ( defined $LogHandler, 'No Log Handler defined - Exiting' );
    my $self = shift;
    $self->{VALUE} = shift;

    my $value = $self->{VALUE} || 'undef';
    $LogHandler->("TIE: STORE $value to $self->{VAR_NAME}");
}


sub FETCH {
    assert ( $#_==0, "Parms: found " . Dumper \@_ );
    assert ( defined $LogHandler, 'No Log Handler defined - Exiting' );
    my $self = shift;

    my $value = $self->{VALUE} || 'undef';

    $LogHandler->("TIE: FETCH $value from $self->{VAR_NAME}");
    return $self->{VALUE};
}


sub set_log_handler {
    assert ( $#_==1, 'Parms' ) if DEBUG;
    my $self = shift;
    $LogHandler = shift;
}



1;