package Text::Expand;
use strict;
use warnings;
use Text::Expand::File;
use fields qw(vars lc loop_context);
our $VERSION = 0.02;

use Carp;

sub new {
    my ($class, %options) = @_;
    $class = ref($class) || $class;
    my __PACKAGE__ $self =
        [Text::Expand::File->new(delete $options{filename},
                                 delete $options{cache})];
    $self->{vars} = {};
    $self->{loop_context} = delete($options{loop_context_vars}) ? 1 : 0;
    $self->{lc} = !delete $options{case_sensitive};
    croak "$class->new does not support dieing on bad params" if
        delete $options{die_on_bad_params};
    croak("Unsupported options to $class->new: " . join(", ", keys %options))
        if keys %options;
    return bless $self, $class;
}

sub param {
    my __PACKAGE__ $self = shift;
    return keys %{$self->{vars}} unless @_;
    if (@_ == 1) {
        if (ref($_[0]) eq "HASH") {
            @{$self->{vars}}{keys %{$_[0]}} = values %{$_[0]};
            return $self;
        }
        croak "Invalid argument type to $self->param" if ref($_[0]);
        return $self->{vars}{$_[0]};
    }
    use vars qw(%vars);
    local *vars = $self->{vars};
    while (@_) {
        my $var = shift;
        $vars{$var} = shift;
    }
    return $self;
}

sub output_reference {
    my __PACKAGE__ $self = shift;
    my $vars = $self->{vars};
    local %Text::Expand::File::cur_levels = (
        ""		=> \$vars,
        "__TOP__"	=> \$vars);
    local $Text::Expand::File::cur_index = 0;
    local $Text::Expand::File::cur_loops = $self->{loop_context} ? 1 : 0;
    local $Text::Expand::File::cur_collect = "";
    $self->[0]->output();
    $Text::Expand::File::cur_collect .= "\n";
    return \$Text::Expand::File::cur_collect;
}

sub output {
    my __PACKAGE__ $self = shift;
    my $vars = $self->{vars};
    local %Text::Expand::File::cur_levels = (
        ""		=> \$vars,
        "__TOP__"	=> \$vars);
    local $Text::Expand::File::cur_index = 0;
    local $Text::Expand::File::cur_loops = $self->{loop_context} ? 1 : 0;
    local $Text::Expand::File::cur_collect = "";
    $self->[0]->output();
    $Text::Expand::File::cur_collect .= "\n";
    return $Text::Expand::File::cur_collect;
}

sub print {
    my __PACKAGE__ $self = shift;
    my $vars = $self->{vars};
    local $Text::Expand::File::cur_collect = shift || \*STDOUT;
    local %Text::Expand::File::cur_levels = (
        ""		=> \$vars,
        "__TOP__"	=> \$vars);
    local $Text::Expand::File::cur_index = 0;
    local $Text::Expand::File::cur_loops = $self->{loop_context} ? 1 : 0;
    $self->[0]->output();
    print $Text::Expand::File::cur_collect "\n";
    return $self;
}

1;
