#!/usr/bin/env python3

import argparse
from pathlib import Path
from string import Template
import sys

DEFAULT_SHEET_TEMPLATE = Path(__file__).parent / 'planche.svg.in'


def parse_args():
    parser = argparse.ArgumentParser(
        description='Make a sheet with 12 stickers')
    parser.add_argument('--template',
                        '-t',
                        default=DEFAULT_SHEET_TEMPLATE,
                        help='path to the sheet template')
    parser.add_argument('--out',
                        '-o',
                        default=sys.stdout,
                        type=argparse.FileType('w'),
                        help='output path (default: stdout)')
    parser.add_argument('--landscape',
                        action='store_true',
                        help='input sticker is in landscape orientation')
    parser.add_argument('sticker',
                        type=argparse.FileType('r'),
                        default=sys.stdin,
                        nargs='?',
                        help='path to the sticker SVG (default: stdin)')

    return parser.parse_args()


def makeplanche(sticker, out, template=DEFAULT_SHEET_TEMPLATE ,landscape=False):
    with open(template) as tpl:
        tpl_data = tpl.read()

    lines = sticker.readlines()
    if lines[0].startswith('<?xml'):
        lines = lines[1:]
    sticker_data = ''.join(lines)

    rotate = "translate(102, 0) rotate(90)" if not landscape else ""

    subs = {
        'sticker': sticker_data,
        'rotate': rotate,
    }

    out.write(Template(tpl_data).substitute(subs))


if __name__ == "__main__":
    makeplanche(**vars(parse_args()))
