package LIMS::Controller::Admin::Lab::Test::PanelTests;

use Data::Dumper;
use LIMS::Local::Sugar;

use Moose;
BEGIN { extends 'LIMS::Base'; }
with (
    'LIMS::Controller::Roles::Misc',
    'LIMS::Controller::Roles::DataMap',
);
__PACKAGE__->meta->make_immutable(inline_constructor => 0);

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

# ------------------------------------------------------------------------------
startmode default ($errs) { # not using $errs
    $self->_debug_path($self->get_current_runmode);

    my $lab_sections = $self->model('LabSection')->get_lab_sections;
    $self->tt_params( lab_sections => $lab_sections );

    if ( my $lab_section_id = $self->query->param('lab_section_id') ) {
        my @tests = do {
            my %args = (
                lab_section_id => $lab_section_id,
                is_active   => 'yes',
            );
            my $o = $self->model('LabTest')->get_section_lab_tests(\%args);
            # sort by field label lc:
            sort { lc $a->field_label cmp lc $b->field_label } @$o;
        }; # warn Dumper \@tests;
        my @panels = map {
            $_->as_tree;
        } grep $_->test_type eq 'panel', @tests;

        $self->tt_params(
            lab_tests => \@tests,
            panels    => \@panels,
        );

        { # get existing data:
            my $data = $self->panel_lab_test_map; # warn Dumper $data;
            $self->tt_params( data => $data );
        }
    }

    return $self->tt_process('admin/lab/test/paneltests/default.tt');
}

# ------------------------------------------------------------------------------
runmode update ($id) {
    $self->_debug_path($self->get_current_runmode);

    my @lab_test_id = $self->query->param('test_id');

    my %data = (
        panel_test_id => $id,
        lab_test_id   => \@lab_test_id,
    ); # warn Dumper \%data;

    my $rtn = $self->model('LabTest')->update_panel_lab_tests(\%data);

    my $url = '/admin/lab_test_panel-tests?lab_section_id='
        . $self->query->param('lab_section_id');

    return $rtn
        ? $self->error($rtn)
        : $self->redirect_after_edit_success($url);
}

1;
