package cz.jzitnik.game.blocks;

import cz.jzitnik.game.Game;
import cz.jzitnik.game.annotations.RightClickLogic;
import cz.jzitnik.game.entities.Block;
import cz.jzitnik.game.handlers.rightclick.RightClickHandler;
import cz.jzitnik.game.sprites.OakDoor;

import cz.jzitnik.tui.ScreenRenderer;

import java.io.Serializable;

@RightClickLogic
public class OakDoorData implements RightClickHandler, Serializable {
    private void change(Block door) {
        door.setSpriteState(switch (door.getSpriteState().get()) {
            case OakDoor.OakDoorState.TOP -> OakDoor.OakDoorState.TOPCLOSED;
            case OakDoor.OakDoorState.BOTTOM -> OakDoor.OakDoorState.BOTTOMCLOSED;
            case OakDoor.OakDoorState.TOPCLOSED -> OakDoor.OakDoorState.TOP;
            case OakDoor.OakDoorState.BOTTOMCLOSED -> OakDoor.OakDoorState.BOTTOM;
            default -> throw new IllegalStateException("Unexpected value: " + door.getSpriteState().get());
        });

        door.setGhost(switch (door.getSpriteState().get()) {
            case OakDoor.OakDoorState.TOP, OakDoor.OakDoorState.BOTTOM -> true;
            case OakDoor.OakDoorState.TOPCLOSED, OakDoor.OakDoorState.BOTTOMCLOSED -> false;
            default -> throw new IllegalStateException("Unexpected value: " + door.getSpriteState().get());
        });
    }

    public void onBlockRightClick(int x, int y, Game game, ScreenRenderer screenRenderer) {
        var blocks = game.getWorld()[y][x];
        var door = blocks.stream().filter(block -> block.getBlockId().equals("oak_door")).toList().getFirst();

        switch (door.getSpriteState().get()) {
            case OakDoor.OakDoorState.TOP, OakDoor.OakDoorState.TOPCLOSED -> {
                var blocks2 = game.getWorld()[y + 1][x];
                var door2 = blocks2.stream().filter(block -> block.getBlockId().equals("oak_door")).toList().getFirst();
                change(door2);
            }
            case OakDoor.OakDoorState.BOTTOM, OakDoor.OakDoorState.BOTTOMCLOSED -> {
                var blocks2 = game.getWorld()[y - 1][x];
                var door2 = blocks2.stream().filter(block -> block.getBlockId().equals("oak_door")).toList().getFirst();
                change(door2);
            }
            default -> throw new IllegalStateException("Unexpected value: " + door.getSpriteState().get());
        }

        change(door);
        game.update(screenRenderer);
    }
}
