package cz.jzitnik.screens.scenes;

import cz.jzitnik.annotations.injectors.InjectDependency;
import cz.jzitnik.annotations.injectors.InjectState;
import cz.jzitnik.events.FullRoomDraw;
import cz.jzitnik.events.KeyboardPressEvent;
import cz.jzitnik.events.MouseAction;
import cz.jzitnik.game.GameState;
import cz.jzitnik.screens.Screen;
import cz.jzitnik.utils.DependencyManager;
import cz.jzitnik.utils.events.EventManager;

public abstract class Scene extends Screen {
    private final Screen[] parts;
    private Screen currentPart;
    private int currentIndex = 0;
    private boolean isRenderedAlready = false;
    private final OnEndAction onEndAction;

    @InjectDependency
    private DependencyManager dependencyManager;

    @InjectState
    private GameState gameState;

    @InjectDependency
    private EventManager eventManager;

    public enum OnEndAction {
        SWITCH_TO_GAME
    }

    public Scene(Screen[] parts, OnEndAction onEndAction) {
        this.parts = parts;
        this.currentPart = parts[0];
        this.onEndAction = onEndAction;
    }

    @Override
    public void fullRender() {
        if (!isRenderedAlready) {
            isRenderedAlready = true;
            render();
        }
    }

    private void render() {
        while (currentPart != null) {
            dependencyManager.inject(currentPart);
            currentPart.fullRender();

            try {
                currentPart = parts[++currentIndex];
            } catch (ArrayIndexOutOfBoundsException e) {
                currentPart = null;
            }
        }

        switch (onEndAction) {
            case SWITCH_TO_GAME -> {
                gameState.setScreen(null);
                eventManager.emitEvent(new FullRoomDraw(true));
            }
        }
    }

    @Override
    public void handleMouseAction(MouseAction event) {
        currentPart.handleMouseAction(event);
    }

    @Override
    public void handleKeyboardAction(KeyboardPressEvent event) {
        currentPart.handleKeyboardAction(event);
    }
}
