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

import cz.jzitnik.game.Game;
import cz.jzitnik.game.annotations.CustomLogic;
import cz.jzitnik.game.annotations.Farmable;
import cz.jzitnik.game.logic.CustomLogicInterface;
import cz.jzitnik.tui.ScreenRenderer;

@CustomLogic
public class FarmableLogic implements CustomLogicInterface {
    private static int RADIUS = 50;
    private static int GROW_LENGTH = 600;

	@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];

                var farmable = blocks.stream().filter(block -> block.getClass().isAnnotationPresent(Farmable.class)).findFirst();

                if (farmable.isEmpty()) {
                    continue;
                }

                var farmableBlock = farmable.get();
                var farmableData = (FarmableData) farmableBlock.getData();

                if (farmableData.getAge() >= GROW_LENGTH) {
                    if (farmableData.getState() >= 2) {
                        // Fully grown
                        continue;
                    }

                    farmableData.setState(farmableData.getState() + 1);
                    farmableData.setAge(0);
                    farmableBlock.setSpriteState(cz.jzitnik.game.sprites.Farmable.getState(farmableData.getState()));
                } else {
                    farmableData.setAge(farmableData.getAge() + 1);
                }
            }
        }
	}

}
