from datetime import datetime
from PIL import Image, ImageDraw, ImageFont

def scale_to_height(icon):
    scale = 100 / icon.height
    return icon.resize((int(icon.width * scale), int(icon.height * scale)))

BLACK  = 0x000000 # 00 BGR
WHITE  = 0xffffff # 01
YELLOW = 0x00ffff # 10
RED    = 0x0000ff # 11
fontmm = ImageFont.truetype('NETWORKSANS-2019-REGULAR.TTF', 20)
font24 = ImageFont.truetype('NETWORKSANS-2019-REGULAR.TTF', 24)
font42 = ImageFont.truetype('NETWORKSANS-2019-REGULAR.TTF', 42)
font64 = ImageFont.truetype('NETWORKSANS-2019-REGULAR.TTF', 64)
fonttime = ImageFont.truetype('NETWORKSANS-2019-REGULAR.TTF', 92)

image = Image.new('RGB', (800, 480), WHITE)
draw = ImageDraw.Draw(image)


# Backing image
with Image.open('ui test 2.png').convert('RGBA') as bg:
    image.paste(bg, (0, 0))

# Time
now = datetime.now()
draw.text((-3, 480-3), f'{now:%H:%M}', font=fonttime, anchor="ls", fill=WHITE)

# Date
dateday = f'{now:%d}'
draw.text((-3, 320), dateday, font=font64, anchor="ls", fill=WHITE)
datedaylength = draw.textlength(dateday, font=font64)
draw.text((datedaylength + 5, 320), f'{now:%b}', font=font64, anchor="lt", fill=WHITE)

# Temperature
temp = 6
temphigh = 12
draw.text((-3, 200), f'{temp}°', font=font64, anchor="ls", fill=WHITE)
draw.text((123, 237), f'{temphigh}', font=font42, anchor="ms", fill=WHITE)

# Rainfall
rainfall = 3
rainthreshold = 5
if rainfall > rainthreshold:
    rainimgpath = 'rain.png'
else:
    rainimgpath = 'sun.png'
draw.text((40, 0), f'{rainfall}', font=font64, anchor="mt")
with Image.open(rainimgpath) as rainimg:
    image.paste(rainimg,mask=rainimg)
draw.text((40, 55), f'mm', font=fontmm, anchor="mt")

image.save('test_before_palette.png')

# Dither into eink palette
pal_image = Image.new('P', (1, 1))
pal_image.putpalette((0x00,0x00,0x00, 0xff,0xff,0xff, 0xff,0xff,0x00, 0xff,0x00,0x00) + (0x00,0x00,0x00)*252)
# Convert the source image to the 4 colors, dithering if needed
image_4color = image.quantize(palette=pal_image, dither=Image.NONE)
image_4color.save('test_after_palette.png')

show_on_screen = False
if show_on_screen:
    import epd7in3g as epd
    try:
        epd.init()
        epd.display(epd.get_buffer(image))
        input('Press Enter to clear')
    finally:
        epd.clear()
        epd.epdconfig.module_exit(cleanup=True)
