import pytest
import os.path
import sys

from ee.kicad.bom import *
from ee.kicad.bom.io import read_bom

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


@pytest.mark.parametrize("s, ref, val, rest", [
    ("C12", "C", 12, ""),
    ("C12n", "C", 12, "n"),
    ("C", "C", sys.maxsize, ""),
    ("Foo", "Foo", sys.maxsize, ""),
    ("+3.0VA1", "+3.0VA1", sys.maxsize, ""),
])
def test_split_ref(s, ref, val, rest):
    assert split_ref(s) == (ref, val, rest)


def test_read_bom_1():
    bom = read_bom(basedir + '/../demo/kicad/bom/A64-OlinuXino_Rev_C.xml')
    assert len(bom.get_components()) == 425


def test_read_bom_2():
    bom = read_bom(basedir + '/../demo/kicad/bom/gw.xml')
    assert len(bom.get_components()) == 165

    r5 = bom.get_component("R5")
    assert r5.ref == "R5"
    assert r5.value == "R0402_100R"
    assert r5["value"] == "R0402_100R"
    assert r5.footprint == "Resistors_SMD:R_0402"
    assert r5.library.name == "gw-cache"
    assert len(r5.fields) == 4
    assert r5.fields["Part Number"] == "CRCW0402100RFKED"
    assert r5["Part Number"] == "CRCW0402100RFKED"
    assert {'ref', 'value', 'Capacitance', 'Color', 'Description', 'Frequency', 'Impedance', 'Inductance',
            'Manufacturer', 'Part Number', 'Resistance'} == bom.all_field_names()

    assert "foo" not in r5
    with pytest.raises(KeyError):
        r5["foo"]


def test_read_bom_2_pandas():
    bom = read_bom(basedir + '/../demo/kicad/bom/gw.xml').to_pandas()
    assert len(bom) == 165

    r5 = bom.loc["R5"]
    #  assert r5.index == "R5"
    assert r5["ref"] == "R5"
    assert r5["value"] == "R0402_100R"
    assert r5["value"] == "R0402_100R"
    #  assert r5["footprint"] == "Resistors_SMD:R_0402"
    #  assert r5.library.name == "gw-cache"
    #  assert len(r5.fields) == 4
    #  assert r5.fields["Part Number"] == "CRCW0402100RFKED"
    assert r5["Part Number"] == "CRCW0402100RFKED"
    #  assert set(['ref', 'value', 'Capacitance', 'Color', 'Description', 'Frequency', 'Impedance', 'Inductance', 'Manufacturer', 'Part Number', 'Resistance']) == bom.all_field_names()

    assert "foo" not in r5
    with pytest.raises(KeyError):
        r5["foo"]