import os
import subprocess
import tempfile

from .makesticker import makesticker
from .makeplanche import makeplanche

OUT_DIR = tempfile.gettempdir()
DEFAULT_DPI = 300

def inkscapize(svg_in, pdf_out):
    png_out = tempfile.mktemp(suffix='.png')
    try:
        cmd = ['inkscape', '--export-type=png', f'--export-filename={png_out}',
                f'--export-dpi={DEFAULT_DPI}', svg_in]
        subprocess.check_call(cmd)

        cmd = ['convert', png_out, pdf_out]
        subprocess.check_call(cmd)
    finally:
        if os.path.exists(png_out):
            os.unlink(png_out)


def generate(request, out_dir):
    """ Generate a sticker sheet.

    request: dict-like with the following fields:
       sticker: mandatory. filename for the sticker
       subs: mandatory. dict-like with key-value template subtitution fields
       landscape: optional. defaults to False

    out_dir: you get it
    """

    # fill in sticker details
    sticker_out = tempfile.mktemp(suffix='.svg')

    try:
        with open(sticker_out, 'w') as stickout:
            landscape = request.get('landscape', False)
            makesticker(os.path.join(out_dir, request['sticker']), stickout,
                    request['subs'], landscape=landscape)

        # make sticker sheet
        planche_out = tempfile.mktemp(suffix='.svg')
        with open(sticker_out, 'r') as stickin:
            with open(planche_out, 'w') as planchout:
                makeplanche(stickin, planchout)

        # process to printable pdf
        pdf_out = tempfile.mktemp(dir=out_dir, suffix='.pdf')
        inkscapize(planche_out, pdf_out)

        return os.path.basename(pdf_out)

    finally:
        if os.path.exists(sticker_out):
            os.unlink(sticker_out)
        if 'planche_out' in locals() and os.path.exists(planche_out):
            os.unlink(planche_out)
