"""Module 15: toggle the EDU PICO USB power relay on GP22."""

import time
import board
import digitalio
import busio
import adafruit_ssd1306


def show_module(oled, number, title, lines):
    """Draw this lesson's OLED screen without an external helper module."""
    oled.fill(0)
    oled.text("({}) {}".format(number, title)[:21], 0, 0, 1)
    for index, line in enumerate(lines[:4]):
        oled.text(str(line)[:21], 0, 16 + index * 11, 1)
    oled.show()


i2c = busio.I2C(board.GP5, board.GP4)
oled = adafruit_ssd1306.SSD1306_I2C(128, 64, i2c, addr=0x3C)
usb_relay = digitalio.DigitalInOut(board.GP22)
usb_relay.switch_to_output(value=False)

try:
    while True:
        usb_relay.value = not usb_relay.value
        status = "Enabled" if usb_relay.value else "Disabled"
        show_module(oled, 15, "USB Relay", (
            "Control: GP22",
            "USB power:",
            status,
        ))
        print("USB relay:", status)
        time.sleep(1.5)
finally:
    usb_relay.value = False
    usb_relay.deinit()
    i2c.deinit()
