package LIMS::Controller::Admin::Config::Diagnoses;

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

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

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

    # first check we have at least 1 diagnostic category defined:
	unless ($self->have_diagnostic_categories) {
        $self->stash( error_msg => $self->messages('admin')->{no_diagnostic_categories} );
        return $self->forward('missing_data');
    }

    my %args = ( sort_by => $self->query->param('sort_by') || '' );

    my $total = $self->model('Base')->get_objects_count('Diagnosis');

    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 all diagnoses:
        my $diagnoses = $self->model('Diagnosis')->get_all_diagnoses(\%args);
        $self->tt_params( diagnoses => $diagnoses );
    }
    { # diagnostic_categories:
        my $diagnostic_categories
            = $self->model('Diagnosis')->get_diagnostic_categories;
        $self->tt_params( categories => $diagnostic_categories );
    }
    { # ICDO3 category - maps ICDO3 to sub-groups (AML, CLL, MCL, etc):
        my $sub_categories = $self->get_icdo_category();
        $self->tt_params( sub_categories => $sub_categories );
    }

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

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

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

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

    my $data = $self->model('Diagnosis')->get_diagnosis($id);

	my $diagnostic_categories
        = $self->model('Diagnosis')->get_diagnostic_categories;

	# how many times has this diagnosis been used?
	my $count = $self->model('Diagnosis')->get_diagnosis_frequency($id);

    # ICDO3 category - maps ICDO3 to sub-groups (AML, CLL, MCL, etc):
    my $sub_categories = $self->get_icdo_category();

    $self->tt_params(
        errs => $errs,
		data => $data,
		count => $count,
		categories => $diagnostic_categories,
        sub_categories => $sub_categories,
	);

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

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

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

    my $id = $self->param('id') || '';  # $self->debug('id:'.$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('diagnosis') )
	|| 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_err = $self->model('Diagnosis')->update_diagnosis($data); # $self->debug($data);
	if ($rtn_err) {
		return self->error($rtn_err);
	}
    # if new lab tests required, get new diagnosis.id & redirect to lab tests page:
    elsif ( $self->query->param('new_labtests') eq 'yes' ) { # required field so will not be undef
        my $diagnosis_name  = $self->query->param('name');
        my $diagnoses_map   = $self->diagnoses_map('name'); # p $diagnoses_map; # need to supply key
        my $diagnosis_id    = $diagnoses_map->{$diagnosis_name}->{id}; # warn $diagnosis_id;
        my $category_id     = $data->{diagnostic_category_id};

        my $url = sprintf '/admin/lab_test_diagnosis-tests?'
            . 'diagnosis_category=%s;diagnosis_id=%s',
                $category_id, $diagnosis_id;
 		return $self->redirect_after_edit_success($url);
	}
    else {
		return $self->redirect_after_edit_success( '/config/diagnoses' );
	}
}

1;
