package LIMS::Controller::Roles::PDF;

use Moose::Role;
use Data::Dumper;
use IO::All;

sub render_pdf { # wkhtmltopdf needs symlink in /usr/bin/
    my ($self, $args) = @_;   

    my $session_id = $args->{session_id}; # needs session_id for chart function	
	my $content    = $args->{content};

    my $data = $self->stash->{request_data}; # warn Dumper $data->as_tree;
    my $patient = $data->patient_case->patient;
    
	my $report_id = sprintf '%s, %s :: %s/%s',
        uc $patient->last_name,
        ucfirst $patient->first_name,
        $data->request_number,
        $data->year - 2000;

	# perl 5.13+ supports: my $foo = $bar =~ s/foo/bar/r; # r = non-descructive
	( my $base_addr = $self->query->url(-base => 1) ) =~ s/\:8080//; # if dev server

    my @args = (
        '--margin-top 7', # combined with header-spacing to provide optimum layout
        '--header-spacing 2', # provide gap between header & banner
		qq!--header-left '$report_id'!,
		qq!--header-right 'Printed on: [date]'!, # [date] replaced by system date (in local format)
        qq!--footer-html $base_addr/cpa_logo.htm!,
        '--header-font-size 8',
        '--margin-bottom 26', # provide space for footer
		'--cookie CGISESSID ' . $session_id,
        '--disable-javascript', # if any
        '--disable-external-links', # no urls
        # '--footer-line', # draw line above - doesn't print
        # '--footer-spacing x', # might need this if long content reaches footer
	);
	
    # create temp file for input to wkhtmltopdf:
    my $tmp_file = sprintf '%s/%s.html',
        $self->cfg->{tmpdir}, $data->id; # warn $tmp_file;
	io($tmp_file)->print(${$content});	# deref $content; save file to disk
    
    my $pdf = `wkhtmltopdf -q @args $tmp_file -`;

	io($tmp_file)->unlink; # delete temp file
    return $pdf;
}

1;


