# -*- coding: utf-8 -*-
from subprocess import call, PIPE
from os import remove, rename
from os.path import dirname
from tempfile import NamedTemporaryFile
from django.template import loader, Context
from django.conf import settings


def process_latex(template, context={}, type='pdf', outfile=None):
    """
    Processes a template as a LaTeX source file.
    Output is either being returned or stored in outfile.
    At the moment only pdf output is supported.
    """

    t = loader.get_template(template)
    c = Context(context)
    r = t.render(c)

    tex = NamedTemporaryFile()
    tex.write(r.encode('utf-8'))
    tex.flush()
    base = tex.name
    items = "log aux pdf dvi png".split()
    names = dict((x, '%s.%s' % (base, x)) for x in items)
    output = names[type]

    if type == 'pdf' or type == 'dvi':
        pdflatex(base, type)
    elif type == 'png':
        pdflatex(base, 'dvi')
        call(['dvipng', '-bg', '-transparent',
              names['dvi'], '-o', names['png']],
             cwd=dirname(base), stdout=PIPE, stderr=PIPE)

    remove(names['log'])
    remove(names['aux'])

    if not outfile:
        o = file(output).read()
        remove(output)
        return o
    else:
        rename(output, outfile)


def pdflatex(file, type='pdf'):
    call([settings.PDFLATEX_PATH, '-interaction=nonstopmode',
          '-output-format', type, file],
         cwd=dirname(file), stdout=PIPE, stderr=PIPE)
