"""Module 12: read the active-low flash-log slide switch on GP15."""

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)
log_switch = digitalio.DigitalInOut(board.GP15)
log_switch.switch_to_input()
last_value = None

try:
    while True:
        enabled = not log_switch.value
        if enabled != last_value:
            status = "Enabled" if enabled else "Disabled"
            show_module(oled, 12, "Log to Flash", (
                "Switch: GP15",
                "Active-low input",
                "Logging: " + status,
            ))
            print("Flash logging:", status)
            last_value = enabled
        time.sleep(0.05)
finally:
    log_switch.deinit()
    i2c.deinit()
