#!/usr/bin/perl

=begin -------------------------------------------------------------------------
emulates function of email_alert() for records matching complex rules:

notification of:
 granulomatous inflammation
 where lab_test = 'TB culture'
 and organisation code like 'RR8%'
 and authorised yesterday
 to chest clinic email contact
=cut ---------------------------------------------------------------------------

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

use strict;
use warnings;

my $JUST_TESTING = 0; # email to raj only

############ recipients from contacts.lib ######################################
my $duration   = $opt_d || 1; # days
my @recipients = qw( chest.clinic.secure );
my @cc = qw( ); # raj.secure
################################################################################

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

use FindBin qw($Bin); # warn $Bin;
use lib $Bin . '/../../../lib';
use LIMS::Local::ScriptHelpers;

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

# get tools from LIMS::Local::ScriptHelpers:
my $sql_lib = $tools->sql_lib();
my $config  = $tools->config();
my $dbix    = $tools->dbix();

# get sql statment:
my $requests = $sql_lib->retr( 'granulomatous_inflammation_status_alert' );
# template:
my $tt_file  = 'request/message/body.tt';
# email subject line:
my $subject   = 'HMDS Diagnosis Status Notice';
# HMDS.LTH user_id for request_history:
my $service_user = $tools->get_server_user_details();

my $result = $dbix->query($requests, $duration);
while (my $vars = $result->hash) { # warn Dumper $vars; next;
	my $data = $tools->get_diagnosis_alert_data($vars);

    my $message_body = $tools->process_template($tt_file, $data);

	my %mail = (
		config  => $config,
		message => $message_body,
		subject => $subject,
	); # warn Dumper \%mail; next;

    my $ok = $tools->send_mail(\%mail, [ @recipients, @cc ]);

    if ($ok) { # log to request_history:
        my %args = (
            request_id => $vars->{request_id},
            user_id    => $service_user->{id},
            action     => 'e-mailed diagnosis alert',
        );
        $tools->log_diagnosis_alert(\%args, \@recipients);
    }
}
