package LIMS::Controller::Admin::User::GroupFunction;

use strict;

use base 'LIMS::Controller::Admin';

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

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

    # a re-direct from update() passes id as param:
    if ( my $id = $self->param('id') ) {
        $self->query->param(id => $id); # for next section and default.tt
    }

    my %data;

    # get user_groups table data:
    my $user_groups = $data{user_groups}
        = $self->model('User')->get_user_groups({sort_by => 'group_label'});

    # highlight no user_groups for tmpl:
    if (! @$user_groups) {
        $self->stash( error_msg => $self->messages('admin')->{no_groups} );
        delete $data{user_groups}; # or mgs fails in tmpl due to empty arrayref
    }

    if ( my $group_id = $self->param('id') || $self->query->param('id') ) {
        # get user_functions, with active => 1 if function.id also in user_group_functions table:
        my $group_functions = $self->model('User')->get_user_group_functions($group_id);

        my $user_functions = $data{user_functions}
            = $self->get_user_functions($group_functions);

        # highlight no user_functions for tmpl:
        if (! @$user_functions) {
            $self->stash( error_msg => $self->messages('admin')->{no_functions} );
            delete $data{user_functions}; # or mgs fails in tmpl due to empty arrayref
        }
    }

    map $self->tt_params($_ => $data{$_}), keys %data;

    return $self->tt_process($errs);
}

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

    my $group_id = $self->param('id') || return $self->error('no id passed to '.$self->get_current_runmode);

    my @function_ids = $self->query->param('function_id'); # $self->debug(\@function_ids);

    unless (@function_ids) {
        $self->flash(warning => $self->messages('group_functions')->{empty_functions_list});
    }

    my %args = (
        function_ids => \@function_ids,
        group_id     => $group_id,
    );

    my $rtn = $self->model('User')->update_user_group_functions(\%args);

    return $rtn  ?
        $self->error($rtn) :
            $self->redirect( $self->query->url . '/admin/user_group-function/default/'.$group_id );
}

1;