package LIMS::Controller::Roles::Misc;

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

# ------------------------------------------------------------------------------
sub get_unique_ids {
	my $self = shift;
	my $data = shift; # arrayref
	
	my %h;

	foreach(@$data) { # warn Dumper $_->as_tree;
		map { # may contain duplicate request.id's:
			my $request_id = $_->request->id;
			$h{$request_id}++
		} @$data;
	}
	
	my @unique_ids = keys %h; # $self->debug(\%request_ids);

	return \@unique_ids;
}

# ------------------------------------------------------------------------------
sub redirect_after_edit_success {
	my $self = shift;
	my $link = shift;
	
    $self->flash( info => $self->messages('action')->{edit_success} );
    return $self->redirect( $self->query->url . $link );	
}

# ------------------------------------------------------------------------------
sub get_lab_test_results_for_lab_section {
	my $self = shift;
	my $args = shift;
	
	my $lab_section_id = $args->{lab_section_id};	
	my $request_id     = $args->{request_id};  # scalar / arrayref
	
	# get lab-tests for lab-section where test-type = test & has_results = yes:
	my %args = (
		lab_section_id => $lab_section_id,
		test_type   => 'test',
		has_results => 'yes',
		is_active   => 'yes',
	);
	
	my $lab_tests = $self->model('LabTest')->get_section_lab_tests(\%args);	
	my @lab_test_ids = map { $_->id } @$lab_tests;
	
	{ # now get lab-test results for all request ids:
		my %args = (
			request_id  => $request_id, # scalar / arrayref
			lab_test_id => \@lab_test_ids,
		);
		
		my $results
			= $self->model('Local')->get_selected_request_lab_test_results(\%args);
		# warn Dumper $results;
		
		my %results_map = ();
		map {
			my $req_id   = $_->request_id; 
			my $lab_test = $_->lab_test->test_name;
			my $result   = $_->result;
			
			$results_map{$req_id}{$lab_test} = $result;
		} @$results; # warn Dumper \%results_map;
		
		return \%results_map;
	}
}

# ------------------------------------------------------------------------------
sub get_lab_test_for_unique_test_name {
	my ($self, $test_name) = @_;
	
	my $lab_test
		= $self->model('LabTest')->get_lab_section_for_test_name($test_name);

	return 0 if scalar @$lab_test > 1;
	
	return $lab_test->[0];
}

# ------------------------------------------------------------------------------
sub extract_patients_and_locations {
	my ($self, $cases) = @_;
	
	my %cases_map = (); # hash for patient.id => referral details
	my @patients  = (); # array of unique patients from $case_iterator
	my %seen      = (); # to facilitate a unique patients list
	
	CASE:
	for my $case (@$cases) {
		my $pid = $case->patient_id; # $self->debug($pid);
	
		push @{ $cases_map{$pid} }, $case->as_tree;
		
		# only need patient details once:
		push @patients, $case->patient->as_tree(deflate => 0) unless $seen{$pid}++;		
	}
	
	return {
		cases_map => \%cases_map,
		patients  => \@patients,
	}
}

1;