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' => 'hmrn_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 params_config : Runmode {
    my $self = shift;
    
    my $categories = $self->model('HMRN')->get_categories;
    $self->tt_params( categories => $categories );
    
    my $category = $self->query->param('category');
    
    # if param_id submitted, update:
    if ( my @ids = $self->query->param('param_id') ) { # warn Dumper \@ids;
        my %args = (
            category  => $category,
            param_ids => \@ids,
        );
        my $rtn = $self->model('HMRN')->update_category_parameter(\%args);
        
        if ($rtn) { return $self->error($rtn) }
        else { $self->flash(info => $self->messages('action')->{edit_success}) }
    }
    # get active params for category:
    if ($category) {
        my $params =
            $self->model('HMRN')->get_active_params_for_category($category);
        $self->tt_params( params => $params );        
    }
    
    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;