package com.ghost.technic;

import com.badlogic.gdx.Game;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Screen;
import com.badlogic.gdx.assets.AssetManager;
import com.badlogic.gdx.graphics.g2d.TextureAtlas;
import com.badlogic.gdx.scenes.scene2d.ui.Skin;
import com.badlogic.gdx.utils.GdxRuntimeException;
import com.ghost.technic.screen.BattlefieldScreen;
import com.ghost.technic.server.Player;
import com.ghost.technic.server.game.GameActionService;
import com.ghost.technic.server.game.GameState;
import com.ghost.technic.server.game.event.EventBus;

import java.util.HashMap;
import java.util.Map;

/** {@link com.badlogic.gdx.ApplicationListener} implementation shared by all platforms. */
public class TechnicClient extends Game {

    private Skin skin;
    private AssetManager assetManager;
    private GameState gameState;
    private GameActionService gameActionService;

    private final Map<Class<? extends Screen>, Screen> screenCache = new HashMap<>();

    @Override
    public void create() {

        skin = new Skin(Gdx.files.internal("ui/uiskin.json"));
        assetManager = new AssetManager();
        assetManager.load("cards/cards.atlas", TextureAtlas.class);
        assetManager.finishLoading();
        Gdx.app.log("TechnicClient | INFO", "Finished loading assets!");

        gameState = new GameState(new EventBus());
        gameActionService = new GameActionService(gameState);

        Player playerOne = Player.builder().name("Alice").build();
        Player playerTwo = Player.builder().name("Bob").build();
        gameState.setPlayers(playerOne, playerTwo);
        gameState.setup();

        // screen
        addScreen(new BattlefieldScreen(skin));
        setScreen(BattlefieldScreen.class);
    }

    public void addScreen(Screen screen) {
        screenCache.put(screen.getClass(), screen);
    }

    public void setScreen(Class<? extends Screen> screenClass) {
        var screen = screenCache.get(screenClass);
        if (screen == null) {
            throw new GdxRuntimeException("Screen " + screenClass.getSimpleName() + " not found in cache");
        }
        super.setScreen(screen);
    }

    public void removeScreen(Screen screen) {
        screenCache.remove(screen.getClass());
    }

    @Override
    public void dispose() {
        for (Screen screen : screenCache.values()) {
            screen.dispose();
        }
        skin.dispose();
    }
}
