package com.tiedup.remake.entities.ai.kidnapper;

import com.tiedup.remake.cells.CellDataV2;
import com.tiedup.remake.cells.CellRegistryV2;
import com.tiedup.remake.entities.EntityKidnapper;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.world.entity.ai.goal.LookAtPlayerGoal;
import net.minecraft.world.entity.player.Player;

/**
 * Custom LookAtPlayerGoal that ignores players who are imprisoned in cells.
 *
 * This prevents kidnappers from staring at players in cells, which is:
 * 1. Creepy behavior
 * 2. Gives the impression that the kidnapper wants to interact with them
 * 3. The prisoner is already being handled by the maid
 */
public class KidnapperLookAtPlayerGoal extends LookAtPlayerGoal {

    private final EntityKidnapper kidnapper;

    public KidnapperLookAtPlayerGoal(
        EntityKidnapper kidnapper,
        Class<Player> target,
        float range
    ) {
        super(kidnapper, target, range);
        this.kidnapper = kidnapper;
    }

    public KidnapperLookAtPlayerGoal(
        EntityKidnapper kidnapper,
        Class<Player> target,
        float range,
        float probability
    ) {
        super(kidnapper, target, range, probability);
        this.kidnapper = kidnapper;
    }

    @Override
    public boolean canUse() {
        if (!super.canUse()) {
            return false;
        }

        // Check if the target player is in a cell
        if (this.lookAt instanceof Player player) {
            if (isPlayerInCell(player)) {
                return false; // Don't look at prisoners in cells
            }
        }

        return true;
    }

    @Override
    public boolean canContinueToUse() {
        if (!super.canContinueToUse()) {
            return false;
        }

        // Stop looking if player enters a cell
        if (this.lookAt instanceof Player player) {
            if (isPlayerInCell(player)) {
                return false;
            }
        }

        return true;
    }

    /**
     * Check if a player is inside a cell (registered as prisoner).
     */
    private boolean isPlayerInCell(Player player) {
        if (!(kidnapper.level() instanceof ServerLevel serverLevel)) {
            return false;
        }

        CellRegistryV2 registry = CellRegistryV2.get(serverLevel);

        // Check if player is registered as a prisoner in any cell
        CellDataV2 cell = registry.findCellByPrisoner(player.getUUID());

        return cell != null;
    }
}
