package LIMS::Controller::Local::Worklist::Histology; 

use base 'LIMS::Base';

use Moose;
with (
	'LIMS::Controller::Roles::Misc',
	'LIMS::Controller::Roles::User',
	'LIMS::Controller::Roles::DataMap',
);
__PACKAGE__->meta->make_immutable(inline_constructor => 0);

use Data::Dumper;

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

	# name of test for this worklist:
	my $test_name = 'cut_up';
	
	# NB: following methods return val already validated in an upstream method:
	my $lab_test = $self->get_lab_test_for_unique_test_name($test_name);

	# all work done in shared method:
	do { $self->_format_lab_test_data($lab_test) }; # don't need rtn val
	
	$self->js_validation_profile('histology_processing');
	
	my $tmpl = 'worklist/local/histology/'.$self->get_current_runmode.'.tt';
	return $self->tt_process($tmpl, $errs);	
}

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

	# name of test for this worklist:
	my $test_name = 'haematoxylin_eosin';
	
	# NB: following methods return val already validated in an upstream method:
	my $lab_test = $self->get_lab_test_for_unique_test_name($test_name);

	# all work done in shared method:
	do { $self->_format_lab_test_data($lab_test) }; # don't need rtn val
	
	$self->js_validation_profile('histology_staining');
	
	my $tmpl = 'worklist/local/histology/'.$self->get_current_runmode.'.tt';
	return $self->tt_process($tmpl, $errs);	
}

# ------------------------------------------------------------------------------
sub blocks_data_update : Runmode {
    my $self = shift; $self->_debug_path($self->get_current_runmode);
	
    unless ( $self->csrf_check_token ) {
        return $self->tt_process('site/csrf_error.tt');
	}

	my @request_ids = $self->query->param('request_id'); # warn Dumper \@request_ids;
	my $reference   = $self->query->param('reference'); # warn $reference;

	unless ( @request_ids && $reference ) {
		$self->flash( error => $self->messages('worklist')->{no_ref_supplied} )
			unless $reference; 
		$self->flash( error => $self->messages('worklist')->{no_request_ids} )
			unless @request_ids;
		return $self->redirect( $self->query->url
			. '/local_worklist?function_name=histology_blocks' );
	}

	my %data = (
		request_ids => \@request_ids,
		reference   => $reference,
	);
	
	my $rtn = $self->model('Local')->update_histology_blocks(\%data);

	if ($rtn) {
		return $self->error($rtn);
	}
	else {
		my $data = $self->model('Request')->get_requests(\@request_ids);
		$self->tt_params( updates => $data ); # warn Dumper $data;
		return $self->tt_process('worklist/local/histology/block_ref.tt');
	}	
}

# ------------------------------------------------------------------------------
sub immunochemistry : Runmode {
	my $self = shift; $self->_debug_path($self->get_current_runmode);
	my $errs = shift; # $self->stash( errs => $errs );
	
	# capture lab_test.id - param 'id' captured in _format_lab_test_data():
	my $lab_test_id = $self->param('Id')
	|| return $self->error( "no 'lab-test id' passed to " . $self->get_current_runmode );

	my $lab_test = $self->model('LabTest')->get_lab_test($lab_test_id);
	$self->tt_params( lab_test_name => $lab_test->field_label );
	
	# all work done in shared method:
	do { $self->_format_lab_test_data($lab_test) }; # don't need rtn val

	$self->js_validation_profile('histology_immunochemistry');
	
	my $tmpl = 'worklist/local/histology/'.$self->get_current_runmode.'.tt';
	return $self->tt_process($tmpl, $errs);	
}

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

    # get linked tests if configured:
    if ( my $yaml = $self->get_yaml_file('worklist_cfg') ) { # warn Dumper $yaml;
        if ( my $data = $yaml->{cut_up_and_processing} ) { # warn Dumper $cfg;
            $self->stash( linked_tests => $data );
        }
    }
	return $self->_do_update('processing');
}

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

	return $self->_do_update('immunochemistry','immunohistochemistry');
}

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

	return $self->_do_update('staining');
}

# ------------------------------------------------------------------------------
sub _format_lab_test_data {
	my ($self, $lab_test) = @_; $self->_debug_path();
	
	# capture request.id:
	my $id = $self->param('id')
	|| return $self->error( "no 'id' passed to " . $self->get_current_runmode );
	
	{ # patient data:
		my $request_data = $self->model('Request')->get_patient_and_request_data($id);
		$self->tt_params( request_data => $request_data );
	}
	{ # request specimen data:
		my $specimen_data = $self->model('Specimen')->get_request_specimens($id);
		my @specimens = map { $_->specimen->sample_code } @$specimen_data;
		$self->tt_params( specimens => \@specimens );
	}
	{ # request_lab_test_history data:
		my %args = (
			request_ids => [$id], # requires arrayref
			field_label => $lab_test->field_label, # history table uses field label
		);		
		my $lab_test_status # returns hashref of { $id => { status => 1 } }
			= $self->lab_test_status_for_field_label_map(\%args)->{$id};
			# warn Dumper $lab_test_status_map; 
		$self->tt_params( lab_test_status => $lab_test_status );			
	}
	{ # get test results for lab_test:
		my %args = (
			request_id => $id,
			lab_section_id => $lab_test->lab_section_id,
		); # warn Dumper \%args;
		my $results = $self->get_lab_test_results_for_lab_section(\%args);
		if ($results) { # hashref of { $id => { field_name => val } }, or 0
			$self->tt_params( results => $results->{$id} );
		}
	}
	{ # lab users:
		my $user_list = $self->get_lab_staff_users;
		$self->tt_params( user_list => $user_list );
	}
	
	# params for hidden fields in tmpl to save downstream lookup:
	$self->tt_params(
		lab_section_id => $lab_test->lab_section_id,
		lab_test_id    => $lab_test->id,
	);
}

# ------------------------------------------------------------------------------
sub _do_update {
	my $self = shift; $self->_debug_path();
	my $type = shift; # eg processing, staining, etc
	my $function_name = shift; # optional var for redirect
	
	# capture request.id:
	my $id = $self->param('id')
	|| return $self->error( "no 'id' passed to " . $self->get_current_runmode );

	my $profile_name = 'histology_'.$type;
	
    my $dfv = $self->check_rm( $type, $self->validate($profile_name) )
    || return $self->dfv_error_page;
	
	my $data = $dfv->valid;
	$data->{request_id} = $id; # add param('id')

    # any linked tests from yaml:
    if ( my $linked_tests = $self->stash->{linked_tests} ) {
        $data->{linked_tests} = $linked_tests;
    }
    
	my $rtn = $self->model('Local')->update_histology_data($data);

	if ($rtn) {
		return $self->error($rtn);
	}
	else {
		$self->flash( info => $self->messages('action')->{edit_success} );

		$function_name ||= $profile_name; # if not already supplied
		return $self->redirect( $self->query->url
			. '/local_worklist?function_name='.$function_name );
	}	
}

1;