package cz.jzitnik.game.logic.services.flowing;

import cz.jzitnik.game.Game;
import cz.jzitnik.game.annotations.CustomLogic;
import cz.jzitnik.game.entities.items.ItemBlockSupplier;
import cz.jzitnik.game.logic.CustomLogicInterface;
import cz.jzitnik.tui.ScreenRenderer;

@CustomLogic
public class LavaWaterLogic implements CustomLogicInterface {
    private static final int RADIUS = 20;

    @Override
    public void nextIteration(Game game, ScreenRenderer ignored) {
        int[] data = game.getPlayerCords();
        var world = game.getWorld();
        int playerX = data[0];
        int playerY = data[1];

        int startX = Math.max(0, playerX - RADIUS);
        int startY = Math.max(0, playerY - RADIUS);
        int endX = Math.min(world[0].length - 1, playerX + RADIUS);
        int endY = Math.min(world.length - 1, playerY + RADIUS);

        for (int y = startY; y <= endY; y++) {
            for (int x = startX; x <= endX; x++) {
                var blocks = world[y][x];
                if (blocks.stream().anyMatch(block -> block.getBlockId().equals("water") && blocks.stream().anyMatch(block2 -> block2.getBlockId().equals("lava")))) {
                    // Generate
                    var water = blocks.stream().filter(block -> block.getBlockId().equals("water")).findFirst().get();
                    var lava = blocks.stream().filter(block -> block.getBlockId().equals("lava")).findFirst().get();

                    var lavaData = (FlowingData) lava.getData();

                    world[y][x].remove(water);
                    world[y][x].remove(lava);

                    if (lavaData.isSource()) {
                        world[y][x].add(ItemBlockSupplier.getBlock("obsidian"));
                    } else {
                        world[y][x].add(ItemBlockSupplier.getBlock("cobblestone"));
                    }
                }
            }
        }
    }
}
