import os
os.environ['PYGAME_HIDE_SUPPORT_PROMPT'] = "hide"
import pygame_widgets
import pygame
from pygame_widgets.button import Button
from pygame_widgets.dropdown import Dropdown
import random

win_width = 600
win_height = 480
win_bg_color = (0, 0, 0)
dice_results = []
text_color = (221, 221, 221)

def draw_results(clicked: bool = False):
    if len(dice_results) == 0: return
    my_string = "Results: "
    for index, element in enumerate(dice_results):
        my_string += str(element)
        if index != len(dice_results) - 1:
            my_string += ", "
    if clicked: print(my_string)
    font_size = 50
    while True:
        arail_20 = pygame.font.SysFont('bauhaus 93', font_size)
        results_text = arail_20.render(my_string, True, text_color)
        if results_text.get_width() < win_width:
            break
        font_size = font_size - 5
    text_x = (win_width // 2) - (results_text.get_width() // 2)
    text_y = win_height - 25 - results_text.get_height() 
    window.blit(results_text,(text_x, text_y))
    
def roll_dice():
    global dice_results
    print("Type of dice: D", side_dropdown.getSelected())
    print("Number of dice: ", numdice_dropdown.getSelected())
    dice_results = []
    for dice in range(0, numdice_dropdown.getSelected()):
        dice_results.append(random.randint(1, side_dropdown.getSelected()))
    draw_results(True)

pygame.init()
window = pygame.display.set_mode((win_width, win_height))
pygame.display.set_caption('Dice Roll')
icon = pygame.image.load(os.path.join("icon", "dieicon_64x.png"))
icon.convert_alpha()
pygame.display.set_icon(icon)

side_dropdown = Dropdown(
    window, 120, 10, 150, 50, name='How many sides',
    choices=[
        'D4',
        'D6',
        'D8',
        'D10',
        'D12',
        'D20',
    ],
    borderRadius=3, colour=pygame.Color(200, 200, 200), values=[4, 6, 8, 10, 12, 20], direction='down', textHAlign='left'
)

numdice_dropdown = Dropdown(
    window, 320, 10, 150, 50, name='Number of Dice',
    choices=[
        '1',
        '2',
        '8',
    ],
    borderRadius=3, colour=pygame.Color(200, 200, 200), values=[1, 2, 8], direction='down', textHAlign='left'
)

button = Button(
    window, 200, 300, 200, 50, text='Roll', fontSize=50, textColor=("red"),
    margin=20, inactiveColour=(243, 243, 243), pressedColour=(0, 255, 0),
    radius=5, onClick=roll_dice, font=pygame.font.SysFont('calibri', 30),
    textVAlign='bottom', 
)

run = True
while run:
    events = pygame.event.get()
    for event in events:
        if event.type == pygame.QUIT:
            run = False
    window.fill(win_bg_color)
    draw_results()

    pygame_widgets.update(events)
    pygame.display.update()

pygame.quit()
quit()
