package Text::Wigwam::Debug;

use strict;
use warnings;
our $VERSION = '0.01';

use Text::Wigwam::Debug::Bug;

use Scalar::Util( qw/ refaddr / );

sub new { return bless [], ref($_[0]) || $_[0]; }

sub add {
     # Adds a new Bug object to the Bugs queue.
    my ($bugs, $new_bug) = @_;
    unshift( @$bugs, $new_bug );
    return $bugs;
}

sub get {
     # Returns an array of Bug objects which contains a
     # single bug object per each template that reported at
     # least one of either: a) an exception (trapped or
     # not); b) debugging information via the API's debug
     # method.
    my ( $self ) = @_;
    my $bugs = { queue => [], list => {} };
     # Merge comments for bugs with matching expression
     # references.
    local $_;
    for (@$self){
       if(0){
        if( exists $bugs->{list}{&_ref_id($_->engine)} ){
            $bugs->{queue}[$bugs->{list}{&_ref_id($_->engine)}]->add_comments( $_->get_comments );
        }
        else {
            $bugs->{list}{&_ref_id($_->engine)} = scalar @{$bugs->{queue}};
            push( @{$bugs->{queue}}, $_ );
        }
       }
       else {
        if( exists $bugs->{list}{&_ref_id($_->expr)} ){
            $bugs->{queue}[$bugs->{list}{&_ref_id($_->expr)}]->add_comments( $_->get_comments );
        }
        else{
            $bugs->{list}{&_ref_id($_->expr)} = scalar @{$bugs->{queue}};
            push( @{$bugs->{queue}}, $_ );
        }
       }
    }
    return $bugs->{queue};
}

sub _ref_id { refaddr $_[0] || 'none' }

1;