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.Bed;

@PlaceHandler("bed")
public class BedPlaceHandler implements CustomPlaceHandler {
    @Override
    public boolean place(Game game, int x, int y) {
        var blocks = game.getWorld()[y][x];
        var blocksLeft = game.getWorld()[y][x - 1];
        var blocksRight = game.getWorld()[y][x + 1];
        var inventory = game.getInventory();

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

            Block block2 = ItemBlockSupplier.getBlock("bed");
            block2.setSpriteState(Bed.BedState.RIGHT);
            blocksRight.add(block2);
            blocksRight.removeAll(blocksRight.stream().filter(Block::isFlowing).toList());

            Block block = inventory.getItemInHand().get().getBlock().get();
            block.setSpriteState(Bed.BedState.LEFT);
            blocks.add(block);
        } else {
            Block block2 = ItemBlockSupplier.getBlock("bed");
            block2.setSpriteState(Bed.BedState.LEFT);
            blocksLeft.add(block2);
            blocksLeft.removeAll(blocksLeft.stream().filter(Block::isFlowing).toList());

            Block block = inventory.getItemInHand().get().getBlock().get();
            block.setSpriteState(Bed.BedState.RIGHT);
            blocks.add(block);
        }
        blocks.removeAll(blocks.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("bed")).toList().getFirst();

        if (block.getSpriteState().get() == Bed.BedState.LEFT) {
            var blocks2 = game.getWorld()[y][x + 1];
            blocks2.removeAll(blocks2.stream().filter(i -> i.getBlockId().equals("bed") || i.getBlockId().equals("breaking")).toList());
        }

        if (block.getSpriteState().get() == Bed.BedState.RIGHT) {
            var blocks2 = game.getWorld()[y][x - 1];
            blocks2.removeAll(blocks2.stream().filter(i -> i.getBlockId().equals("bed") || i.getBlockId().equals("breaking")).toList());
        }

        blocks.removeAll(blocks.stream().filter(i -> i.getBlockId().equals("bed") || i.getBlockId().equals("breaking")).toList());

        return true;
    }
}
