#!/usr/bin/perl

use strict;

use Config::Tiny;
use LIMS::Local::Utils;
use LIMS::Local::Debug;

my $path_to_app_root = LIMS::Local::Utils::find_home
    || die "Couldn't find path to application directory"; # warn $path_to_app_root;

############ configurable settings in settings.txt #####################
my $config = Config::Tiny->read("$path_to_app_root/config/settings.txt"); # $self->debug($config);
my %settings = map %{ $config->{$_} }, qw(local global); # warn Data::Dumper::Dumper \%settings;
########################################################################

my %dbh_params = (
    driver => 'mysql',
    db     => $settings{development_db}, # default to devel db - overridden in mod_perl config
    userid => $settings{db_user_id},
    pwd    => $settings{db_password},
);

my %cfg = (
    settings => \%settings,

	models => {
		PAS => {
			map { $_ => $settings{$_} } grep /\Apas_/, keys %settings
		},
	},

    authen_cfg => { # CAP::Authentication
        DRIVER => [ ], # defined in cgiapp_init()

        LOGIN_SESSION_TIMEOUT => {
#		    IDLE_FOR    => '1m', # dealt with under CUSTOM:
		    EVERY		=> '1d',
		    CUSTOM 		=> sub {
                # This value can be set to a subroutine reference that returns true
                # if the session should be timed out, and false if it is still active.
                my $authen = shift; # have access to UserProfile in $authen, but how to get it out??
                return ( $authen->username ne 'ADMIN' &&
                    ( time() - $authen->last_access ) > $settings{admin_timeout} ); # return 1 if true
                # DEBUG( $authen->{'cgiapp'}{'UserProfile'}{'designation'} );
                # DEBUG('last_access: ' . $authen->last_access); # DEBUG('time: ' . time());
#			    DEBUG(sprintf "authen_cfg, time - last_access = %s [returned %s]",
#				    (time() - $authen->last_access), (time() - $authen->last_access > 1800 ? 1 : 0) );
                # $authen->username = users.username; use time in seconds as eg > '30m' does not work:
            },
		},

        LOGIN_RUNMODE => 'login', # redirect_after_login requires destination field in .tt if used
#       LOGIN_URL     => '/hmds/login', #  causes redirection loop & don't need if using LOGIN_RUNMODE
#       POST_LOGIN_URL     => '', # leave these blank to re-direct to original requested page
#		POST_LOGIN_RUNMODE => '', # will override POST_LOGIN_URL

        STORE => 'Session',
#		STORE => [
#            'Cookie',
#            NAME   => 'HILISAuthentication',
#            SECRET => 'HILIS4',
#            EXPIRY => '30m',
#        ],
    },

    db => {
        production  => $settings{production_db},
        development => $settings{development_db},
    },

    dbh_params => [
		"dbi:$dbh_params{driver}:$dbh_params{db}",
		$dbh_params{userid},
		$dbh_params{pwd},
	],

	dfv_defaults => {
		missing_optional_valid => 1,
		filters => 'trim', # trims white space pre/post field param
		field_filters => { }, # use for forcing field formats eg foo => 'uc' 
		msgs => {
			any_errors 	=> 'dfv_errors', # default err__
			# invalid_separator => '<br />', # needs to be in own <td> to format OK
			prefix 		=> 'error_', # default err_
			invalid    	=> 'invalid', # default 'Invalid'
			missing 	=> 'missing', # already 'Missing'
			format 		=> '<span class="dfv_errors">&#171; %s</span>',
		},
	},

    path_to_app_root => $path_to_app_root,
	path_to_www_docs => $path_to_app_root . '/static/',

    session_config => {
        CGI_SESSION_OPTIONS => [], # defined in cgiapp_init
        DEFAULT_EXPIRY      => '24h', # for forgotten_password expiry
        SEND_COOKIE         => 1,
        COOKIE_PARAMS => {
            -path    => '/',
        },
    },

    session_options_file => {
        Directory => $path_to_app_root.'/sessions',
        IDFile    => $path_to_app_root.'/sessions/cgisession.id',
        IDInit    => 1000, # start at
        IDIncr    => 1, # increment by
    },

    tt_config => {
        TEMPLATE_OPTIONS => {
            WRAPPER      => 'site/tt_wrapper',
            PRE_PROCESS  => 'site/tt_pre_process',
#			PRE_CHOMP    => 1, # screwing template format
			POST_CHOMP   => 1, 
			# need to sort dir permissions for mod_perl & server.pl:
#			COMPILE_DIR  => $path_to_app_root.'/compiled_tmpl',
            INCLUDE_PATH => [
                $path_to_app_root.'/src',
                $path_to_app_root.'/templates',
            ],
        },
    },

    use_cgi_ajax => 1,
);

\%cfg;

__END__
# unused configs:
#    authz_cfg => { # CAP::Authorization config; see update_widget() in pod for eg of complex config
#		DRIVER => [ 'DBI',
#			TABLES => [ 'users u', 'user_functions f', 'user_permission p' ],
#			JOIN_ON => 'u.id = p.user_id AND p.function_id = f.id',
#			USERNAME => 'username',
#            CONSTRAINTS => {
#                function => '__PARAM_1__',
#				 # username => 'ADMIN', # need to make this an 'OR'
#            },
#		],
#       FORBIDDEN_RUNMODE => 'forbidden', # doesn't work as expected - using template->fill() method instead
#    },

#    dbi_driver => [ # using Generic driver now
#        'DBI',
#        DBH => undef, # defined in cgiapp_init()
#    	TABLE       => 'users',
#		CREDENTIALS => [ qw(authen_username authen_password) ], # default & correspond to login form field names
#		CONSTRAINTS => {
#            username => '__CREDENTIAL_1__',
#			active	 => 'yes',
#		},
#    	COLUMNS     => {
#    	    'sha1_base64:password' => '__CREDENTIAL_2__' # using SHA1
#    	},
#    ],

#    dbic_driver => [
#        'DBIC',
#        SCHEMA => undef, # defined in cgiapp_init() $c->param('schema'),
#        CLASS => 'Users', # = My::DBIC::Users
#        FIELD_METHODS => [ qw(username password) ], # qw(user MD5:passphrase)
#        CREDENTIALS => [ qw(authen_username authen_password) ],
#    ],

#    flash => [
#        session_key  => 'FLASH',
#        auto_cleanup => 1,
#    ],

