import random
import pygame
import json

COLORS = ["black", "white", "red", "green", "blue","ice_blue", "yellow", "beige", "brown", "table", "purple"]
COLOR_VALUES = {
    "black": (0, 0, 0),
    "white": (255, 255, 255),
    "red": (255, 0, 0),
    "green": (0, 128, 0),
    "blue": (0, 0, 255),
    "ice_blue": (100, 149, 180),
    "yellow": (255, 255, 0),
    "beige": (220, 220, 190),
    "brown": (165, 42, 42),
    "table": (139, 69, 19),
    "purple": (128, 0, 128),
}

COLOR_GROUP = {
    "white": ["combinats"],
    "green": ["mojitos", "indoor_cocktails"],
    "blue": ["deliver"],
    "ice_blue": ["fridges"],
    "yellow": ["beer"],
    "beige": ["floor"],
    "brown": ["coffee_machine"],
    "table": ["bar_cocktails", "sangrias"],
    "purple": ["outdoor_cocktails"],
    "red": ["wait_position"],
    "black": None,
    "beige": None,

}

GROUP_POSITIONS = {
    "fridges": (3, 39),
    "beer": (39, 40),
    "deliver": (22, 39),
    "indoor_cocktails": (4, 47),
    "mojitos": (4, 47),
    "bar_cocktails": (11, 47),
    "outdoor_cocktails": (11, 35),
    "sangrias": (11, 47),
    "combinats": (2, 43),
    "coffee_machine": (43, 47),
    "wait_position": (32, 42),
    "alone_make_products": (11, 47),
}

class Map:
    def __init__(self, filename):
        self.map = self.loadJson(filename)
        self.width = self.map.get("map_width", 100)
        self.height = self.map.get("map_height", 100)
        self.surface = pygame.Surface((self.width, self.height))
        self.surface.fill((0, 128, 0))  # Rellenar el mapa con color verde
        self.selected_color = "black"
        self.painting = False
    
    def update(self):
        if self.painting:
            self.paint()

    def loadJson(self, filename):
        path = f'simulation/data/maps/{filename}'
        with open(path, 'r') as file:
            data = json.load(file)
        return data
    
    def saveJson(self, filename):
        path = f'simulation/data/maps/{filename}'
        with open(path, 'w') as file:
            json.dump(self.map, file, indent=4)

    def drawMap(self, screen):
        for y in range(self.height):
            for x in range(self.width):
                color = self.getTileColor(x, y)
                pygame.draw.rect(screen, color, (x * 16, y * 16, 16, 16))
    
    def getTileColor(self, x, y):
        tile_key = f"({x},{y})"
        color_name = self.map.get(tile_key, "beige")
        return COLOR_VALUES.get(color_name, (220, 220, 220))  # Default to beige

    def paint(self):
        pos = pygame.mouse.get_pos()
        x, y = pos
        tile_x = x // 16
        tile_y = y // 16
        tile_key = f"({tile_x},{tile_y})"
        self.map[tile_key] = self.selected_color
        self.saveJson('map.json')

    def left_click(self, pos):
        self.painting = not self.painting
        
    def right_click(self, pos):
        #si hay un tile en la posicion, lo borra
        x, y = pos
        tile_x = x // 16
        tile_y = y // 16
        tile_key = f"({tile_x},{tile_y})"
        if tile_key in self.map:
            del self.map[tile_key]
            self.saveJson('map.json')

    def scroll_up(self, pos):
        # rotar colores en sentido horario
        x, y = pos
        tile_x = x // 16
        tile_y = y // 16
        tile_key = f"({tile_x},{tile_y})"
        current_color = self.map.get(tile_key, "beige")
        if current_color in COLORS:
            current_index = COLORS.index(current_color)
            new_index = (current_index + 1) % len(COLORS)
            self.map[tile_key] = COLORS[new_index]
            self.saveJson('map.json')
    
    def scroll_down(self, pos):
        # rotar colores en sentido antihorario
        x, y = pos
        tile_x = x // 16
        tile_y = y // 16
        tile_key = f"({tile_x},{tile_y})"
        current_color = self.map.get(tile_key, "beige")
        if current_color in COLORS:
            current_index = COLORS.index(current_color)
            new_index = (current_index - 1) % len(COLORS)
            self.map[tile_key] = COLORS[new_index]
            self.saveJson('map.json')
    
    def on_c_pressed(self):
        # copiar color del tile bajo el mouse
        pos = pygame.mouse.get_pos()
        x, y = pos
        tile_x = x // 16
        tile_y = y // 16
        tile_key = f"({tile_x},{tile_y})"
        current_color = self.map.get(tile_key, "beige")
        print(f"Copied color: {current_color}")
        if current_color in COLORS:
            self.selected_color = current_color
    
    def is_black_tile(self, x, y):
        tile_key = f"({x},{y})"
        color_name = self.map.get(tile_key, "beige")
        return color_name == "black"
    
    def get_group_position(self, group_name):
        if group_name not in GROUP_POSITIONS:
            print (f"Group '{group_name}' not found in GROUP_POSITIONS.")
        return GROUP_POSITIONS.get(group_name, (0, 0))
    
    def get_groups_in_position(self, x, y):
        tile_key = f"({x},{y})"
        color_name = self.map.get(tile_key, "beige")
        return COLOR_GROUP.get(color_name, [])
    
    def is_position_in_group(self, x, y, group_name):
        # check if the given position belongs to the specified group depending on the color
        groups = self.get_groups_in_position(x, y)
        return groups is not None and group_name in groups
    
    def get_random_group(self):
        import random
        return random.choice(list(GROUP_POSITIONS.keys()))