package DTA::Controller::Formula;
use Moose;
use namespace::autoclean;

BEGIN {extends 'Catalyst::Controller'; }

use utf8;

use Cwd;
use DateTime;
use Digest::MD5 qw( md5_hex );
use File::Path qw( rmtree );
use File::Slurp qw( read_file );
use File::Temp qw( tempfile tempdir );

=head1 NAME

DTA::Controller::Formula - Catalyst Controller

=head1 DESCRIPTION

Catalyst Controller.

=head1 METHODS

=head2 preview

=cut

sub preview : Local {
    my ( $self, $c, $tex ) = @_;

    my $density = defined $c->req->params->{density} ? int($c->req->params->{density}) : 150;
    my $hash    = md5_hex( $tex . $density );
    my $png;

    if ( 0 and -e sprintf( "%s/%s.png", $c->config->{formulacache}, $hash ) ) {
        $png = read_file sprintf( "%s/%s.png", $c->config->{formulacache}, $hash );
    }
    else {
        my $tempdir = tempdir;
        my ( undef, $tempname ) = tempfile( DIR => $tempdir );
        my $cwd = getcwd;
        chdir $tempdir;

        open( my $latexfh, '>:utf8', "$tempname.latex" ) or die $!;
        my $latex = <<"EOT";
\\documentclass[10pt]{article}
\\usepackage{units}
\\usepackage[TS1, T1]{fontenc}
\\usepackage[utf8]{inputenc}
\\usepackage[german]{babel}
\\usepackage{lmodern}
\\pagestyle{empty}

\\DeclareTextSymbol{\\textlongs}{TS1}{115}
\\DeclareTextSymbolDefault{\\textlongs}{TS1}

\\usepackage{amssymb,amsmath}
\\newcommand{\\longs}{\\text{\\textlongs}}
\\newcommand{\\sharps}{\\text{\\ss}}

\\begin{document}
\\begin{displaymath}
$tex
\\end{displaymath}
\\end{document}
EOT

        print $latexfh $latex;
        close $latexfh;

        system "/usr/bin/latex -interaction=nonstopmode $tempname.latex >/dev/null 2>&1";
        system "/usr/bin/dvips -E $tempname -o >/dev/null 2>&1";
        system "/usr/bin/convert -density $density $tempname.ps $tempname.png >/dev/null 2>&1";

        chdir $cwd;
        eval {
            $png = read_file "$tempname.png";
        };
        if ( $@ ) {
            $png = read_file $c->path_to( 'root/static/images/latex-error.png' )."";
        }
        else {
            open( my $hash_fh, '>', sprintf("%s/%s.png", $c->config->{formulacache}, $hash ) ) or die $!;
            print $hash_fh $png;
            close $hash_fh;
        }
        rmtree $tempdir;
    }
    $c->res->header( 'image/png' );
    $c->res->body( $png );
}

__PACKAGE__->meta->make_immutable;

1;
__END__

=head1 AUTHOR

Frank Wiegand

=head1 LICENSE

This library is free software. You can redistribute it and/or modify
it under the same terms as Perl itself.

=cut
