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

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 $categories = $self->model('Diagnosis')->get_diagnostic_categories;
    $self->tt_params( categories => $categories );
    
    if ( my $diagnosis_id = $self->query->param('diagnosis_id') ) {
        {
            my $diagnosis = $self->model('Diagnosis')
                ->get_diagnosis($diagnosis_id);
            $self->tt_params( diagnosis_name => $diagnosis->name );        
        }
        {
            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->diagnosis_lab_test_map(); # warn Dumper $data;
            my $data = $map->{$diagnosis_id};
            $self->tt_params( diagnosis_lab_tests => $data );
        }        
    }
    
    return $self->tt_process('admin/lab/test/diagnosistests/default.tt');
}

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

    my $diagnoses = [];
    
    if ( my $category_id = $self->query->param('category_id') ) { # warn $category_id;
    	$diagnoses = $self->model('Diagnosis')
            ->get_diagnoses_for_category($category_id);
    }    
    return $self->tt_process({ diagnoses => $diagnoses });    
}

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

1;