"""Module 18: count from 0000 to 9999 on the TM1650 display."""

import time
import board
import busio
from edu_pico_lib.TM1650Display import TM1650Display
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)
display = TM1650Display(i2c, brightness=3)
count = 0

try:
    while True:
        text = "{:04d}".format(count)
        display.show(text)
        show_module(oled, 18, "4-Digit Display", (
            "TM1650 on I2C",
            "SDA GP4 / SCL GP5",
            "Display: " + text,
        ))
        print("Display:", text)
        count = (count + 1) % 10000
        time.sleep(0.1)
finally:
    display.off()
    i2c.deinit()
