import pygame
import core.world_loader as world_loader

class StartMenu:
    def __init__(self, worlds):
        self.worlds = worlds
        self.in_start_menu = True
        self.make_button = pygame.Rect(100, 60, 150, 30)
        self.makeing_world = False
        self.world_make_name = ""

    def update(self, screen, screen_size, font):
        pygame.draw.rect(screen, (190, 140, 80), (50, 50, screen_size[0]-100, screen_size[1]-100))
        if self.makeing_world:
            screen.blit(font.render("world name: " + self.world_make_name, True, (0, 0, 0)), (100, 100))
        else:
            pygame.draw.rect(screen, (100, 100, 100), self.make_button)
            screen.blit(font.render("make world", True, (0, 0, 0)), self.make_button)
            for i, world in enumerate(self.worlds):
                rect = pygame.Rect(50, 100+i*70, screen_size[0]-100, 64)
                screen.blit(font.render(world, True, (0, 0, 0)), rect)
                if rect.collidepoint(pygame.mouse.get_pos()) and pygame.mouse.get_pressed()[0]:
                    return True, world
        return False, None

    def handle_event(self, event):
        if event.type == pygame.MOUSEBUTTONDOWN:
            if self.make_button.collidepoint(event.pos):
                self.makeing_world = True
        elif event.type == pygame.KEYDOWN:
            if self.makeing_world:
                if event.key == pygame.K_RETURN:
                    if self.world_make_name not in self.worlds and len(self.world_make_name) >= 3:
                        world_loader.make_world(self.world_make_name)
                        return True
                elif event.key == pygame.K_BACKSPACE:
                    self.world_make_name = self.world_make_name[:-1]
                else:
                    if event.unicode.isprintable():
                        self.world_make_name += event.unicode
        return False