package cz.jzitnik.game.handlers.place.handlers;

import cz.jzitnik.game.annotations.PlaceHandler;
import cz.jzitnik.game.entities.Block;
import cz.jzitnik.game.Game;
import cz.jzitnik.game.entities.items.ItemBlockSupplier;
import cz.jzitnik.game.handlers.place.CustomPlaceHandler;
import cz.jzitnik.game.sprites.OakDoor;

@PlaceHandler("oak_door")
public class DoorPlaceHandler implements CustomPlaceHandler {
    @Override
    public boolean place(Game game, int x, int y) {
        var blocks = game.getWorld()[y][x];
        var blocksTop = game.getWorld()[y - 1][x];
        var blocksBottom = game.getWorld()[y + 1][x];

        if (!blocksTop.stream().allMatch(block -> block.getBlockId().equals("air"))) {
            return false;
        }

        if (blocksBottom.stream().allMatch(Block::isGhost)) {
            return false;
        }

        var inventory = game.getInventory();

        Block block = inventory.getItemInHand().get().getBlock().get();
        block.setSpriteState(OakDoor.OakDoorState.BOTTOMCLOSED);
        blocks.add(block);
        blocks.removeAll(blocks.stream().filter(Block::isFlowing).toList());

        Block block2 = ItemBlockSupplier.getBlock("oak_door");
        block2.setSpriteState(OakDoor.OakDoorState.TOPCLOSED);
        blocksTop.add(block2);
        blocksTop.removeAll(blocksTop.stream().filter(Block::isFlowing).toList());

        inventory.decreaseItemInHand();

        return true;
    }

    @Override
    public boolean mine(Game game, int x, int y) {
        var blocks = game.getWorld()[y][x];
        Block block = blocks.stream().filter(b -> b.getBlockId().equals("oak_door")).toList().getFirst();

        if (block.getSpriteState().get() == OakDoor.OakDoorState.BOTTOM
                || block.getSpriteState().get() == OakDoor.OakDoorState.BOTTOMCLOSED) {
            var blocks2 = game.getWorld()[y - 1][x];
            blocks2.removeAll(blocks2.stream().filter(i -> !i.getBlockId().equals("air") && !i.isMob()).toList());
        }

        if (block.getSpriteState().get() == OakDoor.OakDoorState.TOP
                || block.getSpriteState().get() == OakDoor.OakDoorState.TOPCLOSED) {
            var blocks2 = game.getWorld()[y + 1][x];
            blocks2.removeAll(blocks2.stream().filter(i -> !i.getBlockId().equals("air") && !i.isMob()).toList());
        }

        blocks.removeAll(blocks.stream().filter(i -> !i.getBlockId().equals("air") && !i.isMob()).toList());

        return true;
    }
}
