#!/usr/bin/perl

=begin -------------------------------------------------------------------------
sends new PNH diagnosis message to PNH service contact
=cut ---------------------------------------------------------------------------

use strict;
use warnings;

my $JUST_TESTING = 0; # email to raj only

############ recipients from contacts.lib ######################################
my @recipients = qw( pnh.service.secure );
my @cc = qw( stephen.richards.secure ); # not logged in request_history
my $duration = 1; # days
################################################################################

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( 'new_pnh_alert' );
# template:
my $tt_file  = 'request/message/body.tt';
# email subject line:
my $subject   = 'New PNH Diagnosis 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 new diagnosis alert',
        );
        $tools->do_request_history(\%args, \@recipients);
    }
}
