package LIMS::Local::PDF;

################################################################################
# not in use - replaced by LIMS::Controller::Roles::PDF
################################################################################

use Moose;
has htmldoc => ( is => 'ro', isa => 'HTML::HTMLDoc', lazy_build => 1 );
has config  => ( is => 'ro', isa => 'HashRef', required => 1);
__PACKAGE__->meta->make_immutable;

# use WKHTMLTOPDF; # input file => output file
use HTML::HTMLDoc;
use Data::Dumper;

sub make_pdf {
    my $self = shift;
    my $args = shift; # warn Dumper $args->{session}->id;

    my $htmldoc = $self->htmldoc;
    my $config  = $self->config;

    { # logo:
        my $logo = sprintf '%s/images/%s',
			$config->{path_to_www_docs}, $config->{settings}->{logo_image};

        $htmldoc->set_logoimage($logo);
        # positions; '.' = null; 'l' = logo; 't' = document title
        $htmldoc->set_header('t', '.', 'l');
    }
    { # format:
        $htmldoc->set_bodyfont('Times');
        $htmldoc->set_fontsize(10);
        $htmldoc->set_top_margin(10, 'mm');
        $htmldoc->set_left_margin(15, 'mm');
        $htmldoc->set_right_margin(15, 'mm');
        $htmldoc->set_bottom_margin(10, 'mm');

        # naughty, but setting not otherwise available:
        $self->_set_htmldoc_param('headfootsize', 9);
        # $htmldoc->set_footer('t', 'd', '1'); # doesn't work
    }

    if ( my $html = $args->{html} ) {
        # set session ID in case img called in tmpl (not passed by browser):
        if ( my $session = $args->{session} ) { # only gets passed if needed
            my $session_id = 'CGISESSID=' . $session->id;
            $self->_set_htmldoc_param(cookies => $session_id);
        }
        $htmldoc->set_html_content($html);
    }
    elsif ( my $filename = $args->{file} ) { # warn $filename;
        $htmldoc->set_input_file( join '/', $self->config->{tmpdir}, $filename );
    }

    my $pdf = $htmldoc->generate_pdf(); # my @errs =  $htmldoc->error(); warn @errs if @errs;

    return $pdf->to_string(); # $pdf->to_file('foo.pdf');
}

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

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

    my @args = ( '--cookie CGISESSID ' . $session_id );
    my $pdf = `wkhtmltopdf -q @args $filename -`;
    return $pdf;
}

sub _build_htmldoc {
    my $self = shift;

    my $htmldoc
        = new HTML::HTMLDoc( mode => 'file', tmpdir => $self->config->{tmpdir} );
    return $htmldoc;
}

# need to use undocumented 'private' _set_doc_config method for unsupported params:
sub _set_htmldoc_param {
    my $self = shift;

    $self->htmldoc->_set_doc_config(@_); # pass args straight in
}

1;
