import pygame
from coopgame.gameTemplate import GameTemplate
from coopgame.tilemap import Tilemap, FileTileset
import numpy as np
from cooptools.colors import Color
from coopgame.handleKeyPressedArgs import InputState, InputStateHandler, InputAction, InputEvent, InputEventType, basic_key_actions, CallbackPackage
from coopgame.pygame_k_constant_names import PyKeys, PyMouse
import coopgame.pygamehelpers as phelp
import cooptools.sectors.rect_utils as rutils

file = '../coopgame/assets/tileSets/tmw_desert_spacing.png'

class TileGame(GameTemplate):
    W = 640
    H = 240
    SIZE = W, H

    def __init__(self):


        root_keys = [
            InputAction([InputEvent(ii, event_type=InputEventType.DOWN)], callback=lambda x, d=ii: self.set_value_at_mouse_pos(d.value-48))
            for ii in [PyKeys.K_0, PyKeys.K_1, PyKeys.K_2, PyKeys.K_3, PyKeys.K_4, PyKeys.K_5, PyKeys.K_6, PyKeys.K_7, PyKeys.K_8, PyKeys.K_9]
        ]

        input_state_handler = InputStateHandler(
            quit_callback_package=CallbackPackage(down=lambda x: self.quit()),
            debug_callback_package=CallbackPackage(down=lambda x: self.debug_mode_toggle.toggle()),
            fullscreen_callback_package=CallbackPackage(down=lambda x: self.toggle_fullscreen()),
            key_actions=root_keys + [
                InputAction([InputEvent(PyKeys.K_r, event_type=InputEventType.DOWN)], callback=lambda x: self.tilemap.set_random()),
                InputAction([InputEvent(PyKeys.K_l, event_type=InputEventType.DOWN)], callback=lambda x: self.load_image(file)),
                InputAction([InputEvent(PyMouse.LEFT, event_type=InputEventType.DOWN)], callback=lambda x: self.increment_value_at_mouse_pos(increment=1)),
                InputAction([InputEvent(PyMouse.RIGHT, event_type=InputEventType.DOWN)], callback=lambda x: self.increment_value_at_mouse_pos(increment=-1))
        ])

        super().__init__(input_state_handler=input_state_handler)
        self.screen = pygame.display.set_mode(TileGame.SIZE)
        self.tileset = FileTileset(file)
        self.tilemap = Tilemap(self.tileset,
                               map=np.array([[0, 6, 12],
                                             [1, 7, 13],
                                             [2, 8, 14]]),
                               surface_size=TileGame.SIZE)
        pygame.display.set_caption("Pygame Tiled Demo")
        self.image = None


    def draw(self, frames: int, debug_mode: bool = False):
        self.tilemap.draw(self.screen, outline_tiles_color=Color.RED)

    def load_image(self, file):
        try:
            self.file = file
            self.image = pygame.image.load(file)
            self.rect = self.image.get_rect()
            self.screen = pygame.display.set_mode(self.rect.size)
            pygame.display.set_caption(f'size:{self.rect.size}')

        except Exception as e:
            raise Exception(f"Unable to load file: {file}: {e}")

    def set_value_at_mouse_pos(self, value):
        mouse_grid_pos = rutils.sector_from_coord(
            coord=phelp.mouse_pos(),
            sec_dims=self.tilemap.TileSize
        )
        self.tilemap.set_value(value, positions=[mouse_grid_pos])

    def increment_value_at_mouse_pos(self, increment: int = 1):
        mouse_grid_pos = rutils.sector_from_coord(
            coord=phelp.mouse_pos(),
            sec_dims=self.tilemap.TileSize
        )
        self.tilemap.increment_value(positions=[mouse_grid_pos], increment=increment)

if __name__ == "__main__":

    game = TileGame()
    game.main()