from PIL import Image
from PIL import ImageDraw
from PIL import ImageFont
from datetime import datetime
from time import gmtime, strftime
import time

black = '#000000'
white = '#ffffff'


fontSymbols = ImageFont.truetype("SymbolsNerdFont-Regular.ttf", 18)
fontTitle = ImageFont.truetype("Nunito-SemiBold.ttf", 24)
fontLarge = ImageFont.truetype ("Nunito-ExtraLight.ttf", 18)
fontSmall = ImageFont.truetype ("Nunito-ExtraLight.ttf", 16)
fontVerySmall = ImageFont.truetype("Nunito-ExtraLight.ttf", 10)

def getsize(font, text):
    _, _, right, bottom = font.getbbox(text)
    return (right, bottom)

def reflow_quote(quote, width, font):
    words = quote.split(" ")
    reflowed = ''
    line_length = 0

    for i in range(len(words)):
        word = words[i] + " "
        word_length = getsize(font, word)[0]
        line_length += word_length

        if line_length < width:
            reflowed += word
        else:
            line_length = word_length
            reflowed = reflowed[:-1] + "\n  " + word

    reflowed = reflowed.rstrip()

    return reflowed

def draw_image():
    image = Image.new("P", (400, 300))
    draw = ImageDraw.Draw(image)

    # Draw the top bar
    draw.rectangle((0, 0, 400, 300), fill=white)
    draw.rectangle((0, 0, 400, 40), fill=black)

    # Add the clock
    timeStr = strftime("%H:%M", time.localtime())
    draw.text((10, 10), timeStr, white, fontSmall)

    # Add indoor tempriture
    draw.text((350, 10), "19c", white, fontSmall)

    # Add sections
    ep = 5
    draw.rounded_rectangle((ep, 40+ep, (400/2)-ep, 300-ep), 10, outline=black)
    draw.rounded_rectangle(((400/2) + ep, 40+ep, 400-ep, 300-ep), 10, outline=black)

    # Add tasks
    draw.text((15, 50), 'Tasks', black, fontTitle)

    tasks = [
        {'done': False, 'title': 'Something'}, 
        {'done': True, 'title': 'Get the Modus and Audi MOTs organised'},
        {'done': False, 'title': 'Something else'}, 
        {'done': False, 'title': 'Call locksmith'}, 
        ]

    taskStart = 90
    for task in tasks:
        if task['done']:
            draw.text((15, taskStart), '󰄵', black, fontSymbols)
        else:
            draw.text((15, taskStart), '󰄱', black, fontSymbols)

        reflowedTitle = reflow_quote(task['title'], 170, fontLarge)
        titleSizeW, titleSizeH = getsize(fontLarge, reflowedTitle)
        titleSizeH *= (reflowedTitle.count('\n') + 1)

        draw.text((35, taskStart - 3), reflowedTitle, black, fontLarge)
        taskStart += titleSizeH + (2*ep)

    return image

if __name__ == "__main__":
    img = draw_image()
    img.save('built.bmp')