package LIMS::Local::Role::DiagnosisAlert;

# parses $vars from diagnosis_status_alerts, returns processed template:

use Moose::Role;
use Data::Dumper;
use DateTime::Format::MySQL;

requires qw( get_sql_lib get_settings get_dbix );

has $_ => ( is => 'ro', isa => 'Str', lazy_build => 1) for qw(reporter specimens);

sub get_diagnosis_alert_data {
    my $self = shift;
    my $vars = shift;
    
    my $reporter_sql  = $self->reporter;
    my $specimens_sql = $self->specimens;
    
    my $created_at = DateTime::Format::MySQL->parse_datetime($vars->{created_at});

    my %data = (
        id => $vars->{request_id},
        created_at => $created_at,
        request_number => $vars->{request_number},
        year => $vars->{year},
        
        request_report => {
            status => $vars->{status},
            diagnosis => {
                name => $vars->{diagnosis}
            },            
        },
        
        referrer_department => {
            referrer => {
                name => $vars->{referrer},
            },
        },
        
        patient_case => {
            unit_number => $vars->{unit_number},
            
            referral_source => {
                display_name => $vars->{location},
            },
        
            patient => {
                map { $_ => $vars->{$_} }
                    qw(last_name first_name middle_name nhs_number)
            },
        },
    ); # warn Dumper \%data; next;

    $data{patient_case}{patient}{dob} = $vars->{dob}        
        ? DateTime::Format::MySQL->parse_datetime($vars->{dob} . ' 00:00:00')
        : '';

    # get specimens -> specimen_map:
    my @specimens
        = $self->dbix->query($specimens_sql, $vars->{request_id})->flat;
    my %specimen_map = (
        $vars->{request_id} => { sample_code => \@specimens },
    );

    # get history:
    my %history = ();
    my @reporter
        = $self->dbix->query($reporter_sql, $vars->{request_id})->list;
    @{ $history{reported}{user} }{ qw(last_name first_name) } = @reporter;
    
    my %params = (
        specimen_map => \%specimen_map,
        history      => \%history,
        config       => $self->get_settings,
        data         => \%data,        
    ); # warn Dumper \%params;
    
    return \%params;
}

sub _build_reporter { shift->sql_lib->retr( 'get_reporter_from_request_id' ) }

sub _build_specimens { shift->sql_lib->retr( 'request_specimens' ) }

1;
