import argparse
import ee.kicad as kicad
from ee.tools import mk_parents
from xml.etree import ElementTree
from xml.dom import minidom

parser = argparse.ArgumentParser(description="Create a bom XML file from a KiCAD schematic")

parser.add_argument("--sch",
                    required=True,
                    metavar="SCH",
                    help="The schematic to read")

parser.add_argument("--out",
                    metavar="FILE",
                    help="The output file")

parser.add_argument("--pretty",
                    action='store_true',
                    help="Pretty print the XML")

args = parser.parse_args()

sch = kicad.read_schematic(args.sch)

bom = kicad.to_bom(sch)
xml = ElementTree.tostring(bom, encoding='unicode')

if args.pretty:
    xml = minidom.parseString(xml).toprettyxml(indent="  ")

if args.out:
    mk_parents(args.out)
    with open(args.out, "w") as f:
        f.write(xml)
else:
    print(xml)