from itertools import chain

with open('ft4232h.txt') as f:
    lines = [l.strip() for l in f.read().strip().split('\n') if l.strip()]

def tokenize(line):
    pins, *rest = line.split()
    return (pins.split(','), *rest)

signal_types = {
    'POWER': 'power_in',
    'INPUT': 'input',
    'OUTPU': 'output',
    'I/O': 'bidirectional'
}

def parse(tokens):
    pins0, signal, type0, *rest = tokens
    type = type0 if type0 in signal_types else 'I/O'
    pins = list(map(int, pins0))
    for pin in pins:
        yield pin, signal, signal_types[type]

parse_tokenize = lambda x: parse(tokenize(x))
flat_parse = lambda x: \
    list(sorted(chain.from_iterable(map(parse_tokenize, x)),
                key=lambda x: x[0]))

parsed = flat_parse(lines)
assert(len(list(x[0] for x in parsed)) == 64)
assert(len(set(x[0] for x in parsed)) == 64)

#for pin, signal, type in parsed:
#    print(pin, signal, type)

from kicad_sym import *

split_p = lambda l: "DBUS" not in l[1]
by_name = lambda l: (l[1], l[0])

def make_lib(parsed):
    half_width = 20
    source, sink, other = split_power(parsed)
    source = sorted(source, key=by_name)
    sink = sorted(sink, key=by_name)

    pins, max_len = list(make_pins(other, half_width, split_p))
    all_pins = chain(
        pins,
        make_pin_top(source),
        make_pin_bottom(sink, max_len),
    )
    return lib([
        symbol("FT4232H", "FT4232H",
               all_pins,
               u(-half_width), u(2),
               u(half_width),  u(-(max_len * 2)))
    ])

print(make_lib(parsed))
