package LIMS::Controller::HMRN;

use Moose;
BEGIN { extends 'LIMS::Base'; }
with (
    'LIMS::Controller::Roles::FormData',
);
__PACKAGE__->meta->make_immutable(inline_constructor => 0);

use Data::Dumper;

# ------------------------------------------------------------------------------
sub default : StartRunmode {
    my $self = shift;
    
    return $self->tt_process();    
}

# ------------------------------------------------------------------------------
sub new_diagnoses : Runmode {
    my $self = shift;
    
	# don't need to validate, just get form params:
	my $profile = $self->validate('hmrn_new_diagnoses');
    my $params  = $self->get_data_from_dfv($profile);

    my $cases = $self->model('Request')->get_hmrn_new_diagnoses($params);
    
    { # sort cases by location then name:
        my @data = sort do_sort @$cases; # warn Dumper \@data;
        $self->tt_params( cases => \@data );
    }
    
    { # format date for template display:
        my $from = DateTime->today->subtract( days => $params->{duration} || 7 );
        $self->tt_params( date_from => $from );
    }

    return $self->tt_process;
}

# ------------------------------------------------------------------------------
sub do_sort {
    my $patient_a = $a->patient_case->patient;
    my $patient_b = $b->patient_case->patient;
    
    my $location_a = $a->patient_case->referral_source->display_name;
    my $location_b = $b->patient_case->referral_source->display_name;
    
    return
        $location_a cmp $location_b
            ||
        $patient_a->last_name cmp $patient_b->last_name
            ||
        $patient_a->first_name cmp $patient_b->first_name
}

1;