#!/usr/bin/env perl

# *** replaced with daily/reports.pl Aug 2017

=begin ------------------------------------------------------------------------
* performs daily print run - creates pdf in /backups/print_run dir (or to /tmp
    if JUST_TESTING flag set with getopt -t)
* compiles separate list of trial cases and emails to contacts (unless JUST_TESTING)
* uses same SQLAM query as HILIS 'PrintRun' model class
* ensure fastcgi started if run on test system (http://localhost for charts)
=cut

#===============================================================================
my @recipients = qw(hmds.secure raj); # for clinical trial cases
#===============================================================================

BEGIN {
	use lib '/home/raj/perl5/lib/perl5'; # *must* come before FindBin($Bin)
 	use FindBin qw($Bin); # warn $Bin; exit;
 	use lib $Bin . '/../../../lib';
 	# override default db test:
 	$ENV{ROSEDB_DEVINIT} = "$Bin/../../../config/rosedb_devinit_prod.pl";
}

use autodie;
no autovivification;

use Getopt::Std;
use Modern::Perl;
use Config::Auto;
use Data::Printer;
use SQL::Abstract::More;

getopts('d:t'); # t for testing, d = days to subtract from last_working_date()
our ($opt_t,$opt_d);

my $JUST_TESTING = $opt_t || 0; # saves pdf to /tmp instead of backup dir
$opt_d ||= 0; # default is last working day (don't subtract)

use LIMS::Local::Utils;
use LIMS::Local::Reports;
use LIMS::Local::ScriptHelpers;

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

my $config = $tools->config(); # p $config;
my $today  = $tools->time_now();
my $dbix   = $tools->dbix();

my $start = LIMS::Local::Utils::last_working_date->subtract(days => $opt_d); # p $start;
# end date is today - 1 day (query uses ymd so includes full day to midnight):
my $end = $today->clone->subtract( days => 1 ); # p $start; p $end; exit;

# substitutes LIMS methods required by Role::RecordHandler :
my $lims = LIMS::Local::Reports->new({ tools => $tools }); # also provides model()
# localhost http address - for charts; is_print_request for tt formatting:
$lims->tt_params(
    app_url => 'http://localhost/hilis4', # ensure fastcgi started if run on test system
	is_print_request => 1, # can't use c.get_current_runmode method
);

my $pdf_title = ( $start->ymd eq $end->ymd )
    ? sprintf ( 'Print run [%s]', $start->dmy('.') )
    : sprintf ( 'Print run [%s - %s]', $start->dmy('.'), $end->dmy('.') ); # p $pdf_title;
my $pdf_name = 'printrun_' . $today->ymd . '.pdf';                         # p $pdf_name;
my $pdf_path = $JUST_TESTING ? '/tmp' : '/backups/print_run';              # p $pdf_path;

my $pdf = PDF::API2->new(-file => join '/', $pdf_path, $pdf_name);
$pdf->info( Title => $pdf_title );

my %query_args = (
    start => $start,
    end   => $end,
);

{ # non-trial cases (generate pdfs):
    $query_args{type} = 'non-trial';

    my ($sql, @bind) = $lims->model('PrintRun')
        ->get_query_params(\%query_args); # $dbix->dump_query($sql, @bind); exit;
    my $request_ids = $dbix->query($sql, @bind)->flat; # p $request_ids; exit;

    for my $request_id (@$request_ids) { # warn $request_id; # next;
        my $req = $lims->get_single_request_data($request_id); # L::C::Roles::RecordHandler
        add_new_pdf($req);
        # generate 2nd copy with 'cc' as referrer if copy_to selected:
        if ( $req->{request_options}->{copy_to}->{is_selected} ) { # p $request_id;
            my $o = $req->{data}; # $req->{data} is RDBO object
            $o->referrer_department->referrer->name('cc'); # replace referrer name
            add_new_pdf($req);
        }
    }
    $pdf->save;
}

{ # trial cases (generate list for email):
    $query_args{type} = 'clinical-trial';

    my ($sql, @bind) = $lims->model('PrintRun')
        ->get_query_params(\%query_args); # $dbix->dump_query($sql, @bind); # exit;
    my $request_ids = $dbix->query($sql, @bind)->flat; # p $request_ids; exit;

    my @rows;
    for my $request_id (@$request_ids) { # warn $request_id; # next;
        my $req  = $lims->get_single_request_data($request_id); # L::C::Roles::RecordHandler
        my $data = $req->{data}; # RDBO
# TODO: identify skip_paper_report locations
        push @rows, sprintf '%s :: %s/%s :: %s',
            $data->request_trial->trial->trial_name,
            $data->request_number,
            $data->year - 2000,
            $data->patient_case->referral_source->display_name;
    }
    if (@rows) {
        my %mail = (
            config  => $config,
            subject => 'Clinical trial reports ' . $end->dmy,
            message => join "\n", @rows,
        ); # p %mail;
        $tools->send_mail(\%mail, \@recipients);
    }
}

#-------------------------------------------------------------------------------
sub add_new_pdf {
    my $data = shift;
    my $pdf_string = $lims->format_print_run_report($data);
    my $api = PDF::API2->open_scalar($pdf_string);
    $pdf->importpage($api, $_) for (1 .. $api->pages);
}
