import pygame
from pygame.examples.grid import WINDOW_WIDTH

# pygame initialization
pygame.init()
clock = pygame.time.Clock()

WINDOW_WIDTH = 600
WINDOW_HEIGHT = 600
BUTTON_WIDTH = WINDOW_WIDTH / 4
BUTTON_HEIGHT = WINDOW_HEIGHT / 6

window = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT))
window.fill((255, 255, 255))

# set window title
pygame.display.set_caption("Calculator")
pygame.display.update()

font = pygame.font.SysFont("Verdana", 50)

BORDER_COLOR = (0, 0, 0)
BUTTON_COLOR = (200, 200, 200)
DISPLAY_COLOR = (255, 255, 255)
TEXT_COLOR = (0, 0, 0)

buttons = [
    "7", "8", "9", "/",
    "4", "5", "6", "-",
    "1", "2", "3", "*",
    "0", "=", "c", "+",
    "(", ")", "<", "."
]
data = {
    "display.rect": (0, 0, WINDOW_WIDTH, BUTTON_HEIGHT),
    "display.val": "5 + 10",
}

def center_x(rect1, rect2):
    (x1, y1, w1, h1) = rect1
    (x2, y2, w2, h2) = rect2
    return x2 + (w2 - w1) // 2

def center_y(rect1, rect2):
    (x1, y1, w1, h1) = rect1
    (x2, y2, w2, h2) = rect2
    return y2 + (h2 - h1) // 2

def draw_display():
    display_rect = data["display.rect"]
    val = data["display.val"]
    text = font.render(val, True, TEXT_COLOR)
    text_rect = text.get_rect()
    text_y = center_y(text_rect, display_rect)
    text_x = 10
    pygame.draw.rect(window, DISPLAY_COLOR, display_rect)
    pygame.draw.rect(window, BORDER_COLOR, display_rect, 1)
    window.blit(text, (text_x, text_y))

def draw_button(button):
    button_rect = data[button + ".rect"]
    text = font.render(button, True, TEXT_COLOR)
    text_rect = text.get_rect()
    text_x = center_x(text_rect, button_rect)
    text_y = center_y(text_rect, button_rect)
    pygame.draw.rect(window, BUTTON_COLOR, button_rect)
    pygame.draw.rect(window, BORDER_COLOR, button_rect, 1)
    window.blit(text, (text_x, text_y))

def redraw():
    draw_display()
    for button in buttons:
        draw_button(button)
    pygame.display.update()

def create_buttons():
    x = 0
    y = BUTTON_HEIGHT
    for button in buttons:
        data[button + ".rect"] = (x, y, BUTTON_WIDTH, BUTTON_HEIGHT)
        x += BUTTON_WIDTH
        if x >= WINDOW_WIDTH:
            x = 0
            y += BUTTON_HEIGHT

def run_app():
    app_is_running = True
    while app_is_running == True:
        for event in pygame.event.get():
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_q:
                    app_is_running = False
            elif event.type == pygame.QUIT:
                app_is_running = False

        redraw()
        clock.tick(24)
    pygame.quit()

create_buttons()
run_app()
