import sys
from tetri5.online import MultiplayerService
import pygame
from tetri5.util import ConfigurationManager
from tetri5.util import TextGenerator
from tetri5.util import SoundManager
from tetri5.scene import Scene, TitleScene

# TODO improve game assets https://www.spriters-resource.com/nes/tetris/
# TODO create a util that manages sfx
class Game:

    _current_scene = None

    @classmethod
    def init(cls) -> None:
        pygame.init()
        SoundManager.init()
        TextGenerator.init(ConfigurationManager.get("image", "font"), (20, 20))
        cls._current_scene = TitleScene(Game.change_scene)

        win_width = ConfigurationManager.get("window", "width")
        win_height = ConfigurationManager.get("window", "height")
        win_title = ConfigurationManager.get("window", "title")
        win_icon = ConfigurationManager.get("image", "window-icon")

        cls.fps = ConfigurationManager.get("engine", "fps")
        cls.tile_size = ConfigurationManager.get("engine", "tile-size")
        cls.screen = pygame.display.set_mode((win_width, win_height))
        cls.clock = pygame.time.Clock()
        pygame.display.set_caption(win_title)
        pygame.display.set_icon(pygame.image.load(win_icon))  

    @classmethod
    def update(cls) -> None:
        # TODO write not initialized exception
        elapsed_time = cls.clock.tick(cls.fps)

        if cls._current_scene:
            cls._current_scene.update(elapsed_time)
            
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                MultiplayerService.quit()
                sys.exit()

    @classmethod
    def draw(cls) -> None:
        # TODO write not initialized exception
        if cls._current_scene:
            cls._current_scene.draw(cls.screen)

        # update display
        pygame.display.update()

    @classmethod
    def change_scene(cls, scene: Scene) -> None:
        cls._current_scene = scene


    