#!/usr/bin/perl

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

notification of:
 new/relapsed diagnosis
 where age 13 - 25
 and organisation code like 'RR8%'
 and authorised yesterday
 to Teenage & Young Adult Oncology email contact
=cut ---------------------------------------------------------------------------

use strict;
use warnings;

############ recipients from contacts.lib ######################################
my @recipients = qw( tbd.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( 'young_adult_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;
	}
}


