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

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

BEGIN {
    use FindBin qw($Bin); # warn $Bin;
    use lib "$Bin/../../../lib";
}

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

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

# get tools from LIMS::Local::ScriptHelpers:
my $contacts = $tools->get_contacts();
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;
    
	RECIPIENT:
	foreach my $recipient (@recipients) {
		my $email = $contacts->{$recipient} or next RECIPIENT; # in case doesn't exist
		$mail{recipient} = $email; # warn Dumper $mail{recipient}; next;

		my $rtn = LIMS::Model::Email->send_message(\%mail);
		warn "Error in $0: $rtn" if $rtn;
	}
}


