package eu.oschl.gui.actions;

import eu.oschl.gui.Output;
import eu.oschl.textadventure.Game;
import eu.oschl.textadventure.exceptions.InvalidGameState;
import eu.oschl.textadventure.map.Passage;
import javafx.scene.paint.Color;

public class Enter implements Action {
    private final Game game;

    public Enter(Game game) {
        this.game = game;
    }

    @Override
    public String getId() {
        return "enter";
    }

    @Override
    public String getName() {
        return "Enter";
    }

    @Override
    public String getDescription() {
        return "walk through a passage";
    }

    @Override
    public void execute(String[] args) {
        String input = String.join(" ", args);

        var passages = this.game.getCurrentRoom().getPassages();
        Passage passage = null;

        for (Passage p : passages) {
            if (p.getName().equalsIgnoreCase(input)) {
                passage = p;
                break;
            }
        }

        var printEnterText = !passage.getOtherRoom(game.getCurrentRoom()).wasEntered();

        var result = passage.passThrough(false);

        if (!result) {
            if (game.getCurrentRoom().getEnemy().isPresent()) {
                Output.print(
                        game.getCurrentRoom().getEnemy().get().getName() + " blocks the way. It is only possible to go back.",
                        Color.RED
                );
            } else if (passage.getBlockage().isPresent()) {
                Output.print(passage.getBlockage().get().getDescription(), Color.RED);
            } else {
                Output.print("The passage is blocked.", Color.RED);
            }
            return;
        }

        printSuccessfulPassage(printEnterText);
    }

    /**
     * Prints a message indicating that the player has successfully passed through a passage.
     *
     * @param printEnterText whether to print the enter text of the current room
     */
    private void printSuccessfulPassage(boolean printEnterText) {
        if (game.getLastPassage().isEmpty()) {
            throw new InvalidGameState("Last passages stack is empty even though a passage was passed");
        }

        Output.print("Passed through the ");
        Output.print(game.getLastPassage().get().getName(), Color.YELLOW);
        Output.print(" and entered ");
        Output.print(game.getCurrentRoom().getName(), Color.LIGHTBLUE);
        Output.print(".");

        if (game.getCurrentRoom().isBlockedByEnemy()) {
            Output.printLine();
            Output.print("...", Color.WHITE);
            Output.printLine();
            Output.print("There is somebody in here.", Color.WHITE);
        }

        if (printEnterText && game.getCurrentRoom().getEnterText().isPresent()) {
            Output.printLine();
            Output.printLine();
            Output.print(game.getCurrentRoom().getEnterText().get());
            Output.printLine();
        }
    }
}
