package LIMS::Controller::Admin::Config::Specimens;

use parent 'LIMS::Base';
use LIMS::Local::Sugar;

use Moose;
# extends 'LIMS::Base'; # can't locate object method 'add_callback' in RunmodeDeclare
	with 'LIMS::Controller::Roles::DataMap';
__PACKAGE__->meta->make_immutable(inline_constructor => 0); # if we're not using 'extends'

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

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

    my %args = ( sort_by => 'sample_code' );

    # get total count:
    my $total = $self->model('Base')->get_objects_count('Specimen');

    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 });
    }

	{ # specimens:
		my $specimens = $self->model('Specimen')->get_specimens(\%args);
		$self->tt_params( specimens => $specimens );
	}
	{ # specimen_lab_tests:
		my $specimen_lab_test_map = $self->specimen_lab_test_map;
		$self->tt_params( specimen_lab_test_map => $specimen_lab_test_map );
	}
	
    # get js validation foo_onsubmit & foo_dfv_js vars into tt_params:
    $self->js_validation_profile('specimens');

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

# -------------------------------------------------------------------------------------
runmode edit ($errs, $id) {
    $self->_debug_path($self->get_current_runmode);

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

    my $data = $self->model('Specimen')->get_specimen($id);

    $self->tt_params(
        errs => $errs,
		data => $data,
	);

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

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

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

	# 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('specimens') )
	|| 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('Specimen')->update_specimens($data); # $self->debug($data);

    return $rtn ?
        $self->error($rtn) :
            $self->redirect( $self->query->url . '/config/specimens' );
}

1;