package LIMS::Controller::Admin::Config::Settings;

use strict;

use base 'LIMS::Base';

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

__PACKAGE__->authz->authz_runmodes(	':all' => 'do_admin' );

#-------------------------------------------------------------------------------
sub default : StartRunmode {
    my $self = shift; $self->_debug_path($self->get_current_runmode);

    # retrieve settings from file:
    my $settings = $self->_get_settings();

    $self->tt_params( settings => $settings->{local_admin} );

    # get js validation foo_onsubmit & foo_dfv_js vars into tt_params:
    $self->js_validation_profile('js_config_settings');

    return $self->tt_process( 'admin/config/settings.tt' );
}

#-------------------------------------------------------------------------------
sub edit : Runmode {
    my $self = shift; $self->_debug_path($self->get_current_runmode);

    my $profile = $self->validate('config_settings_profile'); # arrayref

    my $result = $self->form_validator($profile);
    return $self->forward('default') if $result->has_error;

    my $vars = $result->valid; # $self->debug($vars);

    # retrieve settings from file:
    my $all_settings = $self->_get_settings(); # $self->debug($all_settings);

    # only want to update [local_admin] settings:
    my @local_fields = keys %{ $all_settings->{local_admin} }; # $self->debug(\@local_fields);

    # update $all_settings->{local_admin} with values from form:
    map {
        $all_settings->{local_admin}->{$_} = $vars->{$_};
    } @local_fields; #  $self->debug($all_settings);

    # write settings file back to disk:
    my $settings_file = $self->_get_settings_file();
    $all_settings->write($settings_file);

    { # set confirmation messages:
        my $msgs = $self->messages('admin')->{settings};
        $self->flash( info    => $msgs->{update_successful} );
        $self->flash( warning => $msgs->{require_restart}   );
    }
    return $self->redirect( $self->query->url . '/config/settings' );
}

#-------------------------------------------------------------------------------
sub _get_settings {
    my $self = shift; $self->_debug_path();

    my $settings_file = $self->_get_settings_file();
    my $settings = Config::Tiny->read($settings_file); # $self->debug($settings);

    return $settings;
}

#-------------------------------------------------------------------------------
sub _get_settings_file {
    my $self = shift; $self->_debug_path();
    
    my $centre = $self->cfg('settings')->{_centre}; # warn $centre;
    my $path_to_app_root = $self->cfg('path_to_app_root');
    
    my $file = sprintf '%s/config/settings/%s.txt',
        $path_to_app_root, $centre; # 'centre' defined in lims_config.pl    
    return $file;
}

1;
