import os
import subprocess
import tempfile

from .makesticker import makesticker
from .makeplanche import makeplanche

OUT_DIR = tempfile.gettempdir()
DEFAULT_DPI = 300
DESIGNATION_FONTSIZE = 42.6667


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(template, subs, out_dir, landscape=False):
    """ Generate a sticker sheet.

    template: file name for the sticker template
    subs: dict-like with key-value template subtitution fields
    out_dir: you get it
    landscape: optional. defaults to False
    """

    # default designation font size
    subs['designation_fontsize'] = subs.get('designation_fontsize',
                                            DESIGNATION_FONTSIZE)

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

    try:
        with open(sticker_out, 'w') as stickout:
            makesticker(os.path.join(out_dir, template), stickout, subs)

        # 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, landscape=landscape)

        # 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)
