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;

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

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

# ------------------------------------------------------------------------------
sub new_diagnoses : Runmode {
    my $self = shift; $self->_debug_path($self->get_current_runmode);
    
	# 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('HMRN')->get_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;