"""One function, three boards: the parametric example of the scripting lesson, complete and runnable.

The load capacitors come from the crystal's load capacitance CL (its data sheet), not from its
frequency: C1 = C2 = 2 x (CL - Cstray), Cstray about 5 pF. A crystal with no CL given stops the
script with an error instead of guessing. Checked with SKiDL 3.0 and the KiCad 10 libraries.

Run:  python variants.py   ->  breakout_full.net, breakout_minimal.net, breakout_extended.net
"""
from skidl import Net, Part, Pin, ERC, generate_netlist, set_default_tool, KICAD10, reset

set_default_tool(KICAD10)

R_FP = 'Resistor_THT:R_Axial_DIN0207_L6.3mm_D2.5mm_P7.62mm_Horizontal'
C_FP = 'Capacitor_THT:C_Disc_D5.0mm_W2.5mm_P2.50mm'
E12 = [10, 12, 15, 18, 22, 27, 33, 39, 47, 56, 68, 82]


def load_cap_pf(cl_pf, stray_pf=5.0):
    """Nearest E12 value to 2 x (CL - Cstray)."""
    want = 2 * (cl_pf - stray_pf)
    if want <= 0:
        raise ValueError(f'CL {cl_pf} pF is too small for {stray_pf} pF of stray capacitance')
    return min(E12, key=lambda v: abs(v - want))


def make_breakout(name, crystal='16MHz', cl_pf=None, io_pins=14, leds=2):
    if cl_pf is None:
        raise ValueError(f'{name}: give the crystal load capacitance CL from its data sheet')
    reset()                                     # a new, empty circuit for each board
    vcc, gnd, vin = Net('+5V'), Net('GND'), Net('VIN')
    for n in (vcc, gnd, vin):
        n.drive = Pin.drives.POWER

    j1 = Part('Connector', 'Barrel_Jack', ref='J1', footprint='Connector_BarrelJack:BarrelJack_Horizontal')
    j1[1] += vin
    j1[2] += gnd
    u2 = Part('Regulator_Linear', 'LM7805_TO220', ref='U2', footprint='Package_TO_SOT_THT:TO-220-3_Vertical')
    u2['VI'] += vin
    u2['GND'] += gnd
    u2['VO'] += vcc
    for ref, net, value in (('C5', vin, '10uF 25V'), ('C6', vcc, '10uF 16V')):
        c = Part('Device', 'C_Polarized', ref=ref, value=value, footprint='Capacitor_THT:CP_Radial_D5.0mm_P2.50mm')
        c[1] += net
        c[2] += gnd

    u1 = Part('MCU_Microchip_ATmega', 'ATmega328P-P', ref='U1', footprint='Package_DIP:DIP-28_W7.62mm_Socket')
    u1['VCC', 'AVCC'] += vcc
    u1['GND'] += gnd
    for ref in ('C3', 'C4'):
        c = Part('Device', 'C', ref=ref, value='100nF', footprint=C_FP)
        c[1] += vcc
        c[2] += gnd
    aref = Net('AREF')
    u1['AREF'] += aref
    c7 = Part('Device', 'C', ref='C7', value='100nF', footprint=C_FP)
    c7[1] += aref
    c7[2] += gnd

    x1, x2 = Net('XTAL1'), Net('XTAL2')
    u1['XTAL1/PB6'] += x1
    u1['XTAL2/PB7'] += x2
    y1 = Part('Device', 'Crystal', ref='Y1', value=crystal, footprint='Crystal:Crystal_HC49-4H_Vertical')
    y1[1] += x2
    y1[2] += x1
    cap = f'{load_cap_pf(cl_pf)}pF'
    for ref, net in (('C1', x1), ('C2', x2)):
        c = Part('Device', 'C', ref=ref, value=cap, footprint=C_FP)
        c[1] += net
        c[2] += gnd

    rst = Net('RESET')
    u1['~{RESET}/PC6'] += rst
    r1 = Part('Device', 'R', ref='R1', value='10k', footprint=R_FP)
    r1[1] += vcc
    r1[2] += rst
    sw = Part('Switch', 'SW_Push', ref='SW1', footprint='Button_Switch_THT:SW_PUSH_6mm')
    sw[1] += gnd
    sw[2] += rst
    isp = Part('Connector', 'AVR-ISP-6', ref='J2', footprint='Connector_PinHeader_2.54mm:PinHeader_2x03_P2.54mm_Vertical')
    for pin, net in zip(range(1, 7), [u1['PB4'], vcc, u1['PB5'], u1['PB3'], rst, gnd]):
        isp[pin] += net

    # LEDs: the first shows power, the others are on PB5, PB4, PB3 (each also an ISP line)
    for i, (colour, src) in enumerate(zip(['GREEN', 'RED', 'YELLOW', 'BLUE'], [vcc, u1['PB5'], u1['PB4'], u1['PB3']])):
        if i >= leds: break
        a = Net(f'LED{i}')
        r = Part('Device', 'R', ref=f'R{i + 2}', value='330', footprint=R_FP)
        d = Part('Device', 'LED', ref=f'D{i + 1}', value=colour, footprint='LED_THT:LED_D3.0mm')
        r[1] += src
        r[2] += a
        d['A'] += a
        d['K'] += gnd

    pins = ['PD0', 'PD1', 'PD2', 'PD3', 'PD4', 'PD5', 'PD6', 'PD7', 'PB0', 'PB1', 'PB2', 'PB3', 'PB4', 'PB5'][:io_pins]
    j3 = Part('Connector', f'Conn_01x{len(pins):02d}_Pin', ref='J3',
              footprint=f'Connector_PinSocket_2.54mm:PinSocket_1x{len(pins):02d}_P2.54mm_Vertical')
    for k, p in enumerate(pins, 1):
        j3[k] += u1[p]
    unused = [p for p in ['PD0', 'PD1', 'PD2', 'PD3', 'PD4', 'PD5', 'PD6', 'PD7', 'PB0', 'PB1', 'PB2',
                          'PC0', 'PC1', 'PC2', 'PC3', 'PC4', 'PC5'] if p not in pins]
    for p in unused:
        u1[p] += NC     # noqa: F821  (SKiDL puts NC in the builtins)

    ERC()
    generate_netlist(file_=f'{name}.net')
    print(f'{name}: {crystal} with {cap} load capacitors, {len(pins)} I/O pins, LEDs: {leds}')


make_breakout('breakout_full', '16MHz', cl_pf=16, io_pins=14, leds=2)
make_breakout('breakout_minimal', '8MHz', cl_pf=18, io_pins=8, leds=1)
make_breakout('breakout_extended', '20MHz', cl_pf=20, io_pins=14, leds=4)
