#!/usr/bin/env perl

=begin -------------------------------------------------------------------------
diagnosis = 'awaiting final diagnosis, awaiting final review,'
query looks for any request with auth_date less than default 7 days
accepts command-line args -d (days), -t (test mode)
=cut ---------------------------------------------------------------------------

use Getopt::Std;
getopts('d:t'); # days, testing
our($opt_d,$opt_t); # warn $opt_d; exit;

my $JUST_TESTING = $opt_t || 0; # email to ra.jones only
my $duration     = $opt_d || 7; # how many calendar days since authorisation

use strict;
use warnings;

################################################################################
my @recipients = qw( douglas oconnor raj detute );
################################################################################

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;
}
