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} );

    # 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();

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

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

    my $path_to_app_root = $self->cfg('path_to_app_root');

    # write settings file back to disk:
    $all_settings->write("$path_to_app_root/config/settings.txt");

    # set confirmation message:
    $self->flash( info    => $self->messages('admin')->{settings}->{update_successful});
    $self->flash( warning => $self->messages('admin')->{settings}->{require_restart});

    return $self->redirect( $self->query->url . '/config/settings' );
}

#-------------------------------------------------------------------------------
sub _get_settings {
    my $self = shift;

    my $path_to_app_root = $self->cfg('path_to_app_root');
    my $settings = Config::Tiny->read("$path_to_app_root/config/settings.txt"); # $self->debug($config);

    return $settings;
}

1;