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

use strict;

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

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

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

    # first check we have at least 1 lab section defined:
	unless ($self->have_lab_sections) {
        $self->stash( error_msg => $self->messages('admin')->{no_sections} );
        return $self->forward('missing_data');
    }

    # get list of lab_sections table data:
    my $sections = $self->model('LabSection')->get_lab_sections();

    unless ($sections) {
        $self->stash( error_msg => $self->messages('admin')->{no_sections} );
    }

	my %args = ();

	if ( my $lab_section_id = $self->query->param('lab_section_id') ) {
		$args{lab_section_id} = $lab_section_id;
	}

    my $total = $self->model('LabTest')->get_lab_tests_count(\%args);

 	$args{sort_by} = $self->query->param('sort_by')
	|| ['lab_section_id', 'field_label'];

	if ( $total > $self->cfg('settings')->{entries_per_page} ) {
        # invoke pager for template and add limit & offset params to \%args:
        $self->pager({ query => \%args, total => $total });
    }

    # get list of all lab_tests (restricted by lab_section_id if supplied):
	my $tests = $self->model('LabTest')->get_lab_tests(\%args);

    { # get list of specimen types:
        my $data = $self->_get_specimen_types();
        $self->tt_params( specimen_types => $data );
    }
    { # get current lab_test specimen_types:
        my $map = $self->_get_lab_test_specimen_types();
        $self->tt_params( lab_test_specimen_types => $map );
    }
    { # get current lab_section specimen_types:
        my $map = $self->_get_lab_section_specimen_types();
        $self->tt_params( lab_section_specimen_types => $map );
    }
    { # data types for all lab-tests:
		my $map = $self->lab_test_data_types_map; # warn Dumper $data_map;
		$self->tt_params( lab_test_data_types => $map );
	}
    { # test data types:
		my $o = $self->model('Base')
            ->get_objects('LabTestResultDataType', { sort_by => 'description' });
		$self->tt_params( data_types => $o ); # warn Dumper $o;
	}

	$self->tt_params(
        tests    => $tests,
        sections => $sections,
    );

    # get js validation foo_onsubmit & foo_dfv_js vars into tt_params:
    $self->js_validation_profile('lab_tests');

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

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

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

    { # lab tests:
        my $data = $self->model('LabTest')->get_lab_test($id);
        $self->tt_params( data => $data );
    }
    { # lab sections:
        my $sections = $self->model('LabSection')->get_lab_sections(); # no need to sort
        $self->tt_params( sections => $sections );
    }
    { # get list of specimen types:
        my $data = $self->_get_specimen_types();
        $self->tt_params( specimen_types => $data );
    }
    { # get lab_section specimen_types:
        my $map = $self->_get_lab_section_specimen_types();
        $self->tt_params( section_specimen_types => $map );
    }
    { # get lab_test specimen_types for this lab_test.id::
        my $map = $self->_get_lab_test_specimen_types(); # warn Dumper $map;
        $self->tt_params( lab_test_specimen_types => $map->{$id} );
    }
    { # data type:
		my $map = $self->lab_test_data_types_map; # warn Dumper $map;
        my $data_type = $map->{$id}->{description};
		$self->tt_params( test_data_type => $data_type );
	}
    { # test data types:
		my $o = $self->model('Base')
            ->get_objects('LabTestResultDataType', { sort_by => 'description' });
		$self->tt_params( data_types => $o ); # warn Dumper $o;
	}

    # get js validation foo_onsubmit & foo_dfv_js vars into tt_params:
    $self->js_validation_profile('lab_tests');

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

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

	my $id = $self->param('id');

	# put id (if submitted) into params() as _record_id for validation:
    if ( $id ) {
        $self->query->param( _record_id => $id );
    }

    # if param 'id' passed, return error to edit():
    my $error_rm = $id ? 'edit' : 'default';

	my $dfv = $self->check_rm($error_rm, $self->validate('lab_tests') )
	|| return $self->dfv_error_page;

    my $data = $dfv->valid
	|| return $self->forward('default'); # eg if empty param

	# provide 'id' if supplied, so record updated, otherwise new one created:
	if ($id) { $data->{id} = $id; }

    my $rtn = $self->model('LabTest')->update_lab_tests($data);

    return $rtn ?
        $self->error($rtn) :
            $self->redirect( $self->query->url . '/admin/lab_test' ); # safer to redirect after db edit
}

#-------------------------------------------------------------------------------
sub _get_lab_section_specimen_types { # get current lab_section specimen_types:
    my $self = shift;

    my $o = $self->model('Base')->get_objects('LabSectionSampleType');
    my $map;
    for (@$o) {
        $map->{$_->lab_section_id}->{$_->sample_type_id}++;
    }
    return $map;
}

#-------------------------------------------------------------------------------
sub _get_lab_test_specimen_types { # get current lab_section specimen_types:
    my $self = shift;

    my $o = $self->model('Base')->get_objects('LabTestSampleType');
    my $map;
    for (@$o) {
        $map->{$_->lab_test_id}->{$_->sample_type_id}++;
    }
    return $map;
}

#-------------------------------------------------------------------------------
sub _get_specimen_types { # get list of specimen types:
    my $self = shift;

    my $args = { sort_by => 'id' };
    my $o = $self->model('Base')->get_objects('SampleType', $args);
    return $o;
}

1;
