#!/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 strict;
use warnings;

my $JUST_TESTING = 1; # email to raj only

############ recipients from contacts.lib ######################################
my @recipients = qw( chest.clinic.secure raj.secure );
################################################################################

BEGIN {
    use FindBin qw($Bin); # warn $Bin;
    use lib (
        "$Bin/../../../lib",
        '/home/raj/perl5/lib/perl5',
    );
}

use LIMS::Local::ScriptHelpers;
use Data::Dumper;

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

my $result = $dbix->query($requests);
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;
    
    $tools->send_mail(\%mail, \@recipients);
}
