#!/usr/bin/env python3

import argparse
from string import Template
import sys
import typing


def parse_args():
    parser = argparse.ArgumentParser(description='Fill in sticker details')
    parser.add_argument('--out',
                        '-o',
                        default=sys.stdout,
                        type=argparse.FileType('w'),
                        help='output path (default: stdout)')
    parser.add_argument('--dluo',
                        '-d',
                        required=True,
                        help='Date Limite d\'Utilisation Optimale')
    parser.add_argument('--lot', '-l', required=True, help='Numéro de lot')
    parser.add_argument('--quantite', '-q', required=False, help='Quantité (volume ou masse)')
    parser.add_argument('--teneur', '-t', required=False, help='Teneur en sucre')
    parser.add_argument('--fruit', '-f', required=False, help='Quantité de fruits')
    parser.add_argument('--size', '-s', required=False, help='Masse de produit')
    parser.add_argument('--landscape',
                        action='store_true',
                        help='input sticker is in landscape orientation')
    parser.add_argument('sticker', help='path to the sticker template')

    return parser.parse_args()


def makesticker(sticker: str, out: typing.IO, subs: dict, landscape=False):
    with open(sticker) as fin:
        lines = fin.readlines()
        if lines[0].startswith('<?xml'):
            lines = lines[1:]
        sticker_data = ''.join(lines)

    if landscape:
        # Rotate the sticker 90 degrees
        sticker_data = "<g transform=\"rotate(-90,0,0) translate(-102,0)\">{}</g>".format(sticker_data)

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


if __name__ == "__main__":
    args = vars(parse_args())
    subs = {
        'dluo': args.pop('dluo'),
        'lot': args.pop('lot'),
        'teneur': args.pop('teneur'),
        'fruit': args.pop('fruit'),
        'qty': args.pop('quantite'),
        'size': args.pop('size'),
    }
    args['subs'] = subs
    makesticker(**args)
