package LIMS::Local::Role::DiagnosisConfirm;

use Moose::Role;
use Data::Dumper;

# shared by ReportUpdate::do_request_report() & incomplete_requests.pl cron

sub diagnosis_confirmation_required {
    my $self = shift;
	my $args = shift; # expect keys = screen, specimen, lab_tests, lab_sections, yaml
	
=begin # a "final_diagnosis" confirmation IS required if:
	1) request.status = 'authorised' (already been tested for)
	2) no outstanding tests
	3) has a cytogenetics, molecular or FISH results summary
	4) has not been screened as:
		Molecular miscellaneous
		Chimerism sample
		PNH
		Rheumatoid arthritis
		CML follow-up (post-BMT, imatinib, interferon, STI) on PB sample
		CMPD pres & follow-up on PB sample with JAK2 as sole test
=cut

	return 0 unless $args->{yaml}; # eg function not configured
    
	my $specimen = $args->{specimen}; # array(ref) of sample_codes
	my $lab_test = $args->{lab_test}; # AoH (keys = test_name & status)
	my $section  = $args->{section};  # array(ref) of lab_section names
	my $screen   = $args->{screen};   # str
	my $yaml     = $args->{yaml};     # hashref
	
	# get list of lab_test names:
	my @lab_tests = map $_->{test_name}, @$lab_test; # warn Dumper \@lab_tests;

	{ # exempted screens with any sample type:
		# NB - already checked in incomplete_requests.pl
		my $exempt_screens = $yaml->{exempt_all_sample_types}; # arrayref
		return 0 if grep $screen eq $_, @$exempt_screens;		
	} # warn 'here';
	
	{ # exempted screens with specific sample type:
		my $data = $yaml->{exempt_if_sample_type}; # hashref
		while ( my($exempt_screen, $exempt_specimen) = each %$data ) {
			return 0 if $screen eq $exempt_screen
				&& lc(join '', @$specimen) eq lc $exempt_specimen;
		}
	} # warn 'here';
	
	{ # # exempted screens with specific sample type and lab test:
		my $data = $yaml->{exempt_if_sample_type_and_lab_test}; # hashref
		while ( my($exempt_screen, $d) = each %$data ) {
			return 0 if
				$screen eq $exempt_screen &&
				lc(join '', @$specimen) eq $d->{sample} &&
				lc(join '', @lab_tests) eq $d->{test_name};
		}
	} # warn 'here';
	
	{ # require result_summary from molecular, cytogenetics or FISH sections:
		# NB - already checked in incomplete_requests.pl
		my $lab_sections = $yaml->{lab_sections}; # arrayref
		my %map = map { $_ => 1 } @$lab_sections; # create hash from array(ref)
		return 0 unless grep $map{$_}, @$section;
	} # warn 'here';
	
	{ # require all lab_test status = complete:
		# NB - already checked in _diagnosis_confirmation_required()
		my @status = map $_->{status}, @$lab_test; # warn Dumper \@status;
		return 0 if grep $_ ne 'complete', @status;		
	} # warn 'here';
	
	# OK, not an exempt initial_screen/specimen combination, do have necessary
	# result summary & all lab_tests complete so DO need confirmation:
	return 1;	
}

1;
