import os.path

import ee.kicad as kicad

basedir = os.path.dirname(os.path.abspath(__file__))


def dump_schema(sch):
    print("Libraries")
    for l in sch.libraries:
        print("name: {}".format(l.name))

    print("Components")
    for c in sch.components:
        if c.unit != 1:
            continue
        print("REF: {}, fields={}".format(c.ref if c.unit == 1 else "{}/{}".format(c.ref, c.unit), len(c.fields)))
        for f in c.fields:
            print(" {}={}".format(f.name, f.value))


def dump_bom(sch):
    from xml.etree import ElementTree
    from xml.dom import minidom

    print("---")
    bom = kicad.to_bom_xml(sch)
    s = ElementTree.tostring(bom, encoding='unicode')
    print(s)
    xmlstr = minidom.parseString(s).toprettyxml(indent="  ")
    print(xmlstr)
    print("---")


def load(path):
    p = basedir + "/parser/" + path
    print("p={}".format(p))
    sch = kicad.read_schematics(p)
    return sch


def test_demo_1():
    sch = load("parser-demo-1.sch")
    dump_schema(sch)
    dump_bom(sch)
    r101 = sch.get_component("R101")
    assert r101


def test_sch():
    sch = load("foo.sch")
    dump_schema(sch)
    dump_bom(sch)


def test_hierarchical():
    sch = load("hierarchical/hierarchical.sch")
    dump_schema(sch)
    dump_bom(sch)
    assert 3 == len(sch.components)
    assert 3 == len(sch.schematics)
    assert sch.get_component("R101")
    assert sch.get_component("C201")
    assert sch.get_component("L301")