import time
from luma.core.interface.serial import i2c
from luma.oled.device import ssd1306
from PIL import Image, ImageDraw, ImageFont

# Set up I2C device on /dev/i2c-2, address 0x3C
serial = i2c(port=2, address=0x3C)
device = ssd1306(serial, width=128, height=64)

# Create blank image and drawing context
image = Image.new("1", (device.width, device.height))
draw = ImageDraw.Draw(image)

# Draw white background
draw.rectangle((0, 0, device.width, device.height), outline=255, fill=255)

# Draw inner black rectangle
border = 5
draw.rectangle(
    (border, border, device.width - border - 1, device.height - border - 1),
    outline=0,
    fill=0
)

# Load font and text
font = ImageFont.load_default()
text = "Te iubesc <3"

# Use textbbox to get dimensions
bbox = draw.textbbox((0, 0), text, font=font)
text_width = bbox[2] - bbox[0]
text_height = bbox[3] - bbox[1]

# Center the text
x = (device.width - text_width) // 2
y = (device.height - text_height) // 2
draw.text((x, y), text, font=font, fill=255)

# Display on OLED
device.display(image)

# Keep it on screen for 5 seconds
time.sleep(5)

# Clear screen
device.clear()
