package LIMS::Local::Reports;

# used by script/crons/daily/mail_reports.pl to provide missing methods - stash()
# model(), etc required by LIMS methods - format_report(), etc

BEGIN { # load all LIMS::DB::* classes:
    use Data::Dumper;
    use Module::Find;	
	use FindBin qw($Bin); # warn $Bin;
    use lib "$Bin/../../../lib/LIMS/DB"; # actually finds it anyway from @INC
    Module::Find::useall LIMS::DB; # warn Dumper @INC; # DEBUG([@a]);
}

use Moose;
with (
    'LIMS::Role::Base', # model() & render_view()
    'LIMS::Controller::Roles::DataMap',
    'LIMS::Controller::Roles::RecordHandler',
    'LIMS::Controller::Roles::ResultHandler',
);

has session => ( is => 'ro', isa => 'CGI::Session', lazy_build => 1);
has lims_db => ( is => 'ro', isa => 'LIMS::DB', lazy_build => 1);
has tools   => ( is => 'ro', isa => 'LIMS::Local::ScriptHelpers', required => 1 );

__PACKAGE__->meta->make_immutable;

use Template;
use YAML::Tiny;
use LIMS::RDBO;
use CGI::Session;
use LIMS::Local::PDF;
use LIMS::Local::Config;
use CGI::Application::Plugin::Stash;

#-------------------------------------------------------------------------------
sub _debug_path {}

sub cfg { shift->config(@_) }

sub error {
    my ($self, $error) = shift;
    die $error;
}

sub tt_params { # from CAP::TT
    my $self = shift;
    my @data = @_;

    # Define the params stash if it doesn't exist
    $self->{__TT_PARAMS} ||= {};

    if (@data) {
        my $params    = $self->{__TT_PARAMS};
        my $newparams = {};
        if (ref $data[0] eq 'HASH') {
            # hashref
            %$newparams = %{ $data[0] };
        } elsif ( (@data % 2) == 0 ) {
            %$newparams = @data;
        } else {
            die "tt_params requires a hash or hashref!";
        }

        # merge the new values into our stash of parameters
        @$params{keys %$newparams} = values %$newparams;
    }

    return $self->{__TT_PARAMS};
}

# sub render_view { shift->tt_process(@_) }

sub tt_process { # replacement for CAP:TT method, but uses tools->process_template()
    my $self = shift;
    my $tmpl = shift; # warn $tmpl;
    my $vars = shift || {}; # warn Dumper $vars; # none passed from format_report()
    
    my %params = ( %{ $self->tt_params() }, %$vars );

    # Add c => $self in as a param for convenient access to sessions and such
    $params{c} ||= $self;

    my $html = $self->tools->process_template($tmpl, \%params);

    return \$html;
}

sub config {
    my $self = shift;
    my $key  = shift; # optional - if called as $cfg->('foo')
    
    my $cfg = LIMS::Local::Config->instance;
    
    if ($key) {
        return $cfg->{$key};
    }
    else {
        return $cfg;
    }
}

sub _build_lims_db {
    return LIMS::RDBO->init_db;
}

sub _build_session {
    return CGI::Session->new();
}

1;