#!/usr/bin/env perl

=begin -------------------------------------------------------------------------
diagnosis = 'awaiting final diagnosis, awaiting final review,'
=cut ---------------------------------------------------------------------------

use strict;
use warnings;

my $JUST_TESTING = 0; # email to ra.jones only

################################################################################
my @recipients = qw( douglas oconnor raj detute );
my $duration = 7; # how many calendar days since authorisation
################################################################################

use lib '/home/raj/perl5/lib/perl5';
use Data::Dumper;

use FindBin qw($Bin); # warn $Bin;
use lib $Bin . '/../../../lib';
use LIMS::Local::ScriptHelpers;
use DateTime::Format::MySQL;
use IO::All;

# get tools from LIMS::Local::ScriptHelpers:
my $tools = LIMS::Local::ScriptHelpers->new();
$tools->test_only($JUST_TESTING);

my $sql_lib = $tools->sql_lib();
my $config  = $tools->config();
my $dbix    = $tools->dbix();

my $query = $sql_lib->retr('awaiting_final_diagnosis');
my $result = $dbix->query($query, $duration)->hashes;
exit unless @$result; # warn ref $result;

# auth_date to datetime:
$_->{auth_date} = DateTime::Format::MySQL->parse_date($_->{auth_date})
    for @$result;
my $incomplete = _get_incomplete_requests($result);

# email subject line:
my $subject = sprintf 'Awaiting final diagnosis/review [%s]', scalar @$result;
# template:
my $tmpl  = 'cron/awaiting_final_diagnosis.tt';
# data for tt:
my %h = (
    requests   => $result,
    incomplete => $incomplete,
);
# message:
my $message = $tools->process_template($tmpl, \%h);
#io($Bin.'/awaiting_final_diagnosis.htm')->print($message) if $JUST_TESTING;

my %mail = (
    content => 'html',
	config  => $config,
	message => $message,
	subject => $subject,
); # warn Dumper \%mail; exit;

$tools->send_mail(\%mail, \@recipients);

sub _get_incomplete_requests {
    my $data = shift;
    my @request_ids = map $_->{id}, @$data;

    my $query = $sql_lib->retr('awaiting_final_diagnosis_incomplete_tests');
    my $result = $dbix->query($query, @request_ids)->map;
    return $result;
}
