package LIMS::Controller::PAS;

use strict;

use base 'LIMS::Base';

use LIMS::Local::PAS;
use LIMS::Local::Utils; # format_postcode()

use Data::Dumper;

#-------------------------------------------------------------------------------
sub search : StartRunmode {
    my $self = shift; $self->_debug_path($self->get_current_runmode);

    my $patient_id =
        $self->param('id') || $self->query->param('_patient_id'); # warn $case_id;

    my ($patient, @unit_numbers);
    
    if ($patient_id) {
        $patient = $self->model('Patient')->get_patient($patient_id);
        
        my $cases = $self->model('PatientCase')->get_cases_by_patient_id($patient_id);

        my %all_unit_numbers =
            map  { $_->unit_number, 1 }
            grep { $_->unit_number ne $_->meta->column('unit_number')->default }
            @$cases;
            
        push @unit_numbers, $_ for sort keys %all_unit_numbers;    
    }
    else { # no match in patients table - re-use submitted form params:
        my $vars = $self->query->Vars; # warn Dumper $vars;
        
        # freeze vars in session for transfer to registration form if no PAS match:
        unless ($vars->{_do_pas_search}) { # ie return from pas search - don't want these vals
            $self->session->param( patient_search_params => { %$vars } ); # needs to be in assoc. array format 1st
        }
        
        my %new_patient = map { $_ => $vars->{$_} }
            qw(last_name first_name nhs_number unit_number); # NOT same as unit_numbers !!
        if ( my $dob = $vars->{dob} ) { # convert to ymd format for Utils::to_datetime():
            @{$vars}{qw(year month day)} = split '-', $dob;
        }
        $new_patient{dob} = LIMS::Local::Utils::to_datetime($vars); # .tt requires DT
        
        $patient = \%new_patient; # supply in required hashref format
        if ( my $unit_number = $self->query->param('unit_number') ) {
            push @unit_numbers, $unit_number; # only if exists, or get [ '' ] in tt
        }
        # clear all query params to prevent fill_form() loading into form fields:
        # $self->query->delete_all(); # not required if not using fill_form()
    }
    
    $self->tt_params(
        patient => $patient,
        unit_numbers => \@unit_numbers,
    );
    
    return $self->tt_process; # return $self->fill_form($self->tt_process); why ??
}

#-------------------------------------------------------------------------------
sub do_search : Runmode {
    my $self = shift; $self->_debug_path($self->get_current_runmode);

    my $data = $self->query->Vars; # $self->debug($data);

    my $number_of_vars = grep $data->{$_},
        qw(last_name first_name dob unit_number nhs_number post_code); # warn $number_of_vars;

    unless ( $number_of_vars >= 2 ) { # warn 'Insufficient no. of vars';
        $self->flash( error => $self->messages('demographics')->{pas_insufficient_vars} );
        return $self->forward('search');
    }

    my @pas_config_settings = qw(pas_address pas_username pas_pwd);

    my %pas_config = map {
        $_ => $self->cfg('settings')->{$_};
    } @pas_config_settings; # $self->debug(\%pas_config);

    # need all required PAS config settings, or return:
    return if grep ! $pas_config{$_}, @pas_config_settings;

    if ( my $zip = $data->{post_code} ) {
        my $formatted_postcode = LIMS::Local::Utils::format_postcode($zip);
        $data->{post_code} = $formatted_postcode;
    }

    my %args = (
        patient  => $data,
        config   => \%pas_config,
        messages => $self->messages('demographics'),
    );

    my $pas = LIMS::Local::PAS->new(\%args);

    my $result = $pas->query; # $self->debug($result);

    my $is_arrayref = sub { ref shift eq 'ARRAY' };
    
    $self->tt_params(
        pas_results => $result,
        is_arrayref => $is_arrayref,
    );

    return $self->forward('search');
}

1;
