package LIMS::Local::LIMS;

# used by cron scripts to provide required LIMS methods - stash(), model(), etc

BEGIN {
    $ENV{USE_FILE_SESSIONS} = 1; # use disk dir for sessions, not db table

    $ENV{RDBO_DEBUG_ON} = $ENV{RDBO_DEBUG} = 0; # just to make sure
}

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 Template;
use YAML::Tiny;
use LIMS::RDBO;
use CGI::Simple;
use CGI::Session;
use LIMS::Local::Config;
use CGI::Application::Plugin::Stash;

use Moose;
with (
    'LIMS::Role::Base', # model() & render_view()
);

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;

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

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

sub query { new CGI::Simple } # for C::R::PDF query()

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 {
    my $self = shift;

    my $session = CGI::Session->new();

    my $cfg = $self->config('settings'); # warn Dumper $cfg;
    # create user profile for model - so far only need ID of service user:

    my $server_name = $cfg->{server_username}; # warn Dumper $server_name;
    my $user = LIMS::DB::User->new(username => $server_name)->load
    || die "no such username '$server_name' in users table";

    my $user_profile = { id => $user->id };
    $session->param( UserProfile => $user_profile );
    return $session;
}

1;