#!/usr/bin/perl

=begin -------------------------------------------------------------------------
emails list of cases registered during previous week for all locations
=cut ---------------------------------------------------------------------------

use strict;
use warnings;

my $JUST_TESTING = 1; # email to ra.jones only

############ recipients from contacts.lib ######################################
my @recipients = qw( raj.secure );
my $duration = 7; # over past number of days
################################################################################

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

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

#-------------------------------------------------------------------------------
my $date    = DateTime->today->dmy;
my $subject = "Cases registered week ending $date";
#-------------------------------------------------------------------------------

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

my $contacts = $tools->get_contacts();
my $sql_lib  = $tools->sql_lib();
my $config   = $tools->config(); 
my $dbix     = $tools->dbix();

my $query = $sql_lib->retr('cases_registered');
    
my $result = $dbix->query($query, $duration);

my @rows;
while (my $ref = $result->array) { # warn Dumper $vars; next;
    push @rows, $ref;
}

my $msg = join "\n", map {
	sprintf "%-10s %-12s %-15s %-12s %-12s %s", map $_ ||= 'NULL', @{$_};
} @rows; # print $msg; exit;

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

RECIPIENT:
foreach my $recipient (@recipients) { # warn Dumper $_; next;
	my $email = $contacts->{$recipient} or next RECIPIENT; # in case doesn't exist
	next RECIPIENT if $JUST_TESTING && $email !~ /ra\.jones/;
	
	$mail{recipient} = $email; # warn Dumper $mail{recipient}; next;
	my $rtn = LIMS::Model::Email->send_message(\%mail);
	warn "Error in $0: $rtn" if $rtn;
}
