package cz.jzitnik.game.handlers.pickup.handlers;

import cz.jzitnik.game.Game;
import cz.jzitnik.game.annotations.PickupHandler;
import cz.jzitnik.game.entities.Block;
import cz.jzitnik.game.entities.items.Item;
import cz.jzitnik.game.handlers.pickup.CustomPickupHandler;
import cz.jzitnik.game.logic.services.flowing.FlowingData;

import java.util.List;

@PickupHandler("bucket")
public class BucketPickupHandler implements CustomPickupHandler {
    private List<Item> returnItem(List<Block> blocks) {
        var block = blocks.stream().filter(Block::isFlowing).findFirst().get();

        return block.getDrops();
    }

    @Override
    public boolean handle(Game game, int x, int y) {
        var world = game.getWorld();
        var blockOptional = game.getWorld()[y][x].stream().filter(Block::isFlowing).findFirst();
        if (blockOptional.isEmpty()) {
            return false;
        }

        var block = blockOptional.get();
        if (!((FlowingData) block.getData()).isSource()) {
            return false;
        }

        var returnItems = returnItem(world[y][x]);

        game.getInventory().decreaseItemInHand();
        game.getInventory().addItem(returnItems);

        if (!block.getBlockId().equals("water") || !isInfiniteWaterSource(game, x, y)) {
            world[y][x].remove(world[y][x].stream().filter(Block::isFlowing).findFirst().get());
        }

        return true;
    }

    private boolean isInfiniteWaterSource(Game game, int x, int y) {
        var world = game.getWorld();

        var leftBlock = world[y][x - 1].stream().filter(Block::isFlowing).findFirst();
        var rightBlock = world[y][x + 1].stream().filter(Block::isFlowing).findFirst();

        if (leftBlock.isPresent() && ((FlowingData) leftBlock.get().getData()).isSource()) {
            return true;
        }

        return rightBlock.isPresent() && ((FlowingData) rightBlock.get().getData()).isSource();
    }
}
