#!/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('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):
    with open(template) as tpl:
        tpl_data = tpl.read()

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

    subs = {
        'left0': sticker_data,
        'left1': sticker_data,
        'left2': sticker_data,
        'left3': sticker_data,
        'left4': sticker_data,
        'left5': sticker_data,
        'right0': sticker_data,
        'right1': sticker_data,
        'right2': sticker_data,
        'right3': sticker_data,
        'right4': sticker_data,
        'right5': sticker_data,
    }

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


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