# A VT-200 like serial terminal display for RP-2040 and tiny .96" OLED Display
import board
import busio
import displayio
import time

try:
    from i2cdisplaybus import I2CDisplayBus
except ImportError:
    from displayio import I2CDisplay as I2CDisplayBus


import terminalio
from adafruit_display_text import label
import adafruit_displayio_ssd1306

uart0 = busio.UART(board.GP0, board.GP1, baudrate=115200)

displayio.release_displays()

oled_reset = board.GP21

# Initialize I2C on GP26 (SDA) and GP27 (SCL)
i2c = busio.I2C(scl=board.GP27, sda=board.GP26)
# i2c = board.STEMMA_I2C()  # For using the built-in STEMMA QT connector on a microcontroller
display_bus = I2CDisplayBus(i2c, device_address=0x3D, reset=oled_reset)

WIDTH = 128
HEIGHT = 64  # Change to 64 if needed
BORDER = 5
LINE_HEIGHT = HEIGHT // 6

display = adafruit_displayio_ssd1306.SSD1306(display_bus, width=WIDTH, height=HEIGHT)

# Make the display context
splash = displayio.Group()
display.root_group = splash

color_bitmap = displayio.Bitmap(WIDTH, HEIGHT, 1)
color_palette = displayio.Palette(1)
color_palette[0] = 0xFFFFFF  # White

line = 0
text = ["", "", "", "", "", "", ""]
LINES = 7
text_line = [None, None, None, None, None, None, None]
for i in range(LINES):
    text_line[i] = label.Label(terminalio.FONT, text=text[i], color=0xFFFFFF, x=2, y=LINE_HEIGHT * i - 1)
    splash.append(text_line[i])

mode = "linefeed-up" # "linefeed-up" (fancy) OR "scan-down"
while True:
    dataIn = uart0.readline()
    if dataIn is not None:
        line = (line + 1) % LINES    
        # convert bytearray to string
        text[line] = ''.join([chr(b) for b in dataIn])
        print(text[line], end="")
                
        if mode == "scan-down" :
            text_line[line].text = text[line]
        elif mode == "linefeed-up" :
            l = line
            text_line[l].y = LINE_HEIGHT * -1 - 1
            text_line[l].text = text[l]
            text_line[l].y = LINE_HEIGHT * 6 - 1
            l = (l + 1) % LINES
            text_line[l].y = LINE_HEIGHT * 0 - 1
            l = (l + 1) % LINES
            text_line[l].y = LINE_HEIGHT * 1 - 1
            l = (l + 1) % LINES
            text_line[l].y = LINE_HEIGHT * 2 - 1
            l = (l + 1) % LINES
            text_line[l].y = LINE_HEIGHT * 3 - 1
            l = (l + 1) % LINES
            text_line[l].y = LINE_HEIGHT * 4 - 1
            l = (l + 1) % LINES
            text_line[l].y = LINE_HEIGHT * 5 - 1