#!/usr/bin/env python3

import argparse
from string import Template
import sys
import os
import csv
from subber import Subber

TEMPLATES_DIR = "templates"
OUT_DIR = "autogenerated_svgs"

JAM_DESIGNATION_FONTSIZE_DEFAULT = 42.6667
JAM_DESIGNATION_FONTSIZE_SMALL   = 36


templates = {
    'aromate': f"{TEMPLATES_DIR}/Aromate.svg",
    'chocolat': f"{TEMPLATES_DIR}/Chocolat.svg",
    'confiture': f"{TEMPLATES_DIR}/Confiture.svg",
    'pesto': f"{TEMPLATES_DIR}/Pesto.svg",
    'sirop': f"{TEMPLATES_DIR}/Sirop.svg",
    'tisane': f"{TEMPLATES_DIR}/Tisane.svg",
    'tisanenoel': f"{TEMPLATES_DIR}/Tisane Noël.svg",
    'sel': f"{TEMPLATES_DIR}/Sel.svg",
}

ALLERGEN_BEGIN_STYLE = '<tspan style="font-weight:bold">'
ALLERGEN_END_STYLE = '</tspan>'


def parse_args():
    parser = argparse.ArgumentParser(description='Renew whole lineup from template and list of subs')
    parser.add_argument('--list', required=True, help='Lineup file')

    return parser.parse_args()


def main():
    args = parse_args()

    with open(args.list) as csvfile:
        reader = csv.reader(csvfile, delimiter=';', quotechar='"')
        for row in reader:
            template = templates[row[0]]
            outfile = f"{OUT_DIR}/{row[5]}"
            with open(outfile, 'w') as out:
                # TODO Fix bold formatting with allergen and parenthesis
                ingredients = [e.strip() for e in row[2].split(',')]
                ingredients = [e if not e.startswith('*') else ALLERGEN_BEGIN_STYLE + e[1:] + ALLERGEN_END_STYLE for e in ingredients]
                ingredients_sub = ", ".join(ingredients)
                AB_logo_visibility = 'inline' if row[6] == 'True' else 'none'
                # Set the 4 linear-gradient stop colors if they are set in the csv, otherwise default to the template's background color
                if 7+4 <= len(row):
                   gradient_color0, gradient_color1, gradient_color2, gradient_color3 = row[7:7+4]
                else:
                   gradient_color0 = gradient_color1 = gradient_color2 = gradient_color3 = row[4]

                subs = {
                        'designation': row[1].strip(),
                        'ingredients': ingredients_sub,
                        'description': row[3].strip(),
                        'color': row[4],
                        'gradient_color0': gradient_color0,
                        'gradient_color1': gradient_color1,
                        'gradient_color2': gradient_color2,
                        'gradient_color3': gradient_color3,
                        'AB': AB_logo_visibility,
                        'designation_fontsize': JAM_DESIGNATION_FONTSIZE_DEFAULT,
                }
                s = Subber(subs)
                s.sub(template, out)


if __name__ == "__main__":
    main()
