# SPDX-FileCopyrightText: 2025 Jay Martin, added lines for Adafruit's Playground
# SPDX-FileCopyrightText: 2025 Scott Shawcroft, written for Adafruit Industries
# SPDX-FileCopyrightText: Copyright (c) 2021 Melissa LeBlanc-Williams for Adafruit Industries
#
# SPDX-License-Identifier: Unlicense

"""Simple test script for 3.7" 240x416 monochrome display (ThinkInk_370_Mono_BAAMFGN)."""

import time
import alarm
import board
import busio
import displayio
from fourwire import FourWire
import adafruit_uc8253
from adafruit_pcf8523.pcf8523 import PCF8523

displayio.release_displays()

if "EPD_MOSI" in dir(board):  # Feather RP2040 ThinkInk
    spi = busio.SPI(board.EPD_SCK, MOSI=board.EPD_MOSI, MISO=None)
    epd_cs = board.EPD_CS
    epd_dc = board.EPD_DC
    epd_reset = board.EPD_RESET
    epd_busy = board.EPD_BUSY
else:
    spi = board.SPI()  # Uses SCK and MOSI
    epd_cs = board.D9
    epd_dc = board.D10
    epd_reset = board.D8  # Set to None for FeatherWing
    epd_busy = board.D7  # Set to None for FeatherWing
display_bus = FourWire(
    spi, command=epd_dc, chip_select=epd_cs, reset=epd_reset, baudrate=1000000
)
time.sleep(1)

display = adafruit_uc8253.UC8253(
    display_bus,
    width=416,
    height=240,
    busy_pin=epd_busy,
    rotation=270,
    vcom_cdi=0x97,
)

g = displayio.Group()

# read the weekday from rtc module
i2c = board.STEMMA_I2C()
rtc = PCF8523(i2c)
dtm = rtc.datetime
wdy = dtm.tm_wday

# select the bitmap image of the day
if wdy == 6:
    pic = displayio.OnDiskBitmap("/sun.bmp")
elif wdy == 0:
    pic = displayio.OnDiskBitmap("/mon.bmp")
elif wdy == 1:
    pic = displayio.OnDiskBitmap("/tue.bmp")
elif wdy == 2:
    pic = displayio.OnDiskBitmap("/wed.bmp")
elif wdy == 3:
    pic = displayio.OnDiskBitmap("/thu.bmp")
elif wdy == 4:
    pic = displayio.OnDiskBitmap("/fri.bmp")
elif wdy == 5:
    pic = displayio.OnDiskBitmap("/sat.bmp")

# display the image
t = displayio.TileGrid(pic, pixel_shader=pic.pixel_shader)
g.append(t)
display.root_group = g
display.refresh()

# set an alarm for 12:15 a.m. to rerun code.py
current_sec = (dtm.tm_hour * 60 * 60) + (dtm.tm_min * 60) + dtm.tm_sec
wait_sec = 86400 - current_sec + 900  # seconds until 12:15 a.m.
time_alarm = alarm.time.TimeAlarm(monotonic_time=time.monotonic() + wait_sec)
alarm.exit_and_deep_sleep_until_alarms(time_alarm)