import xml.etree.ElementTree as etree
import pathlib

import numpy as np
from svgpath2mpl import parse_path


SVG_PATH = pathlib.Path(__file__).parent / "./TSmeta.svg"


def main():
    tree = etree.parse(SVG_PATH)

    parent_map = {c: p for p in tree.iter() for c in p}
    root = tree.getroot()
    path_elems = root.findall(".//{http://www.w3.org/2000/svg}path")

    marks = {}
    for i, path_elem in enumerate(path_elems):
        _id = path_elem.attrib["id"]
        p = parse_path(path_elem.attrib["d"])

        verts = p.vertices
        offset = verts.max(axis=0) - (verts.max(axis=0) - verts.min(axis=0)) / 2
        for vert in p._vertices:
            vert[0] -= offset[0]
            vert[1] -= offset[1]
            vert[1] *= -1  # somewhere things get flipped, not sure why
        p._vertices = np.round(
            p.vertices, 2
        )  # arbitrary to clean up the file a little.
        marks[_id] = p.deepcopy()

    outpath = pathlib.Path(__file__).parent.parent / "tcmarkers/markers.py"
    with open(outpath, "wt") as outf:
        outf.write(
            """
# Autogenerated Paths for each marker from SVG file. 
# Don't edit manually. Edit SVG and regenerate this file. 

from matplotlib.path import Path
from numpy import array, uint8


"""
        )
        for key, path in marks.items():
            outf.write(
                f"{key}_path = {path}"
            )  # relying on the matplotlib.path.Path repr
            outf.write("\n\n")


if __name__ == "__main__":
    main()
