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

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 $summary_id = $self->query->param('results_summary_id') ) { # warn $summary_id;
        {
            my $summary = $self->model('Result')
                ->get_results_summary_option($summary_id);
            $self->tt_params( results_summary => $summary->description );        
        }
        {
            my %data;
            my $all_tests = $self->model('LabTest')->get_lab_tests();
            for (@$all_tests) {
                my $section = $_->lab_section->section_name;
                push @{ $data{$section} }, $_->as_tree;
            }
            $self->tt_params( section_tests => \%data );
        }
        { # get existing data:
            my $map  = $self->results_summary_lab_test_map(); # warn Dumper $map;
            my $data = $map->{$summary_id};
            $self->tt_params( result_summary_lab_tests => $data );
        }        
    }    
    return $self->tt_process('admin/lab/test/resultsummarytests/default.tt');
}

# ------------------------------------------------------------------------------
# ajax function called from select menu:
runmode results_summaries {
    $self->_debug_path($self->get_current_runmode);

    my $results_summaries = [];
    
    if ( my $section_id = $self->query->param('section_id') ) { # warn $section_id;
    	$results_summaries = $self->model('Result')
            ->get_results_summary_options_for_section($section_id);
    }    
    return $self->tt_process({ results_summaries => $results_summaries });    
}

# ------------------------------------------------------------------------------
runmode update ($id) {
    $self->_debug_path($self->get_current_runmode);
    
    my @lab_test_id = $self->query->param('test_id');
    
    my %data = (
        summary_id   => $id,
        lab_test_id  => \@lab_test_id,
    ); # warn Dumper \%data;
    
    my $rtn = $self->model('LabTest')->update_results_summary_lab_tests(\%data);
    
    my $url = '/admin/lab_test_result-summary-tests?results_summary_id=' . $id;
        
    return $rtn
        ? $self->error($rtn)
        : $self->redirect_after_edit_success($url);
}

1;