/*
 * Copyright (c) 2026 盐灯水母
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at https://mozilla.org/MPL/2.0/.
 */

package com.remains_cave.entity.ai;

import com.remains_cave.entity.SkeletonKingEntity;
import net.minecraft.world.entity.Mob;
import net.minecraft.world.entity.ai.goal.Goal;

import java.util.EnumSet;

public class StayNearKingGoal extends Goal {
    private final Mob mob;
    private SkeletonKingEntity king;
    private final double speedModifier;
    private final double maxDistance;
    private final double minDistance;
    private int findKingTimer = 0;

    public StayNearKingGoal(Mob mob, double speedModifier, double maxDistance, double minDistance) {
        this.mob = mob;
        this.speedModifier = speedModifier;
        this.maxDistance = maxDistance;
        this.minDistance = minDistance;
        this.setFlags(EnumSet.of(Flag.MOVE));
    }

    @Override
    public boolean canUse() {
        if (--findKingTimer <= 0) {
            findKingTimer = 40 + mob.getRandom().nextInt(20);
            // 查找附近 32 格内的骷髅王
            king = mob.level().getNearestEntity(SkeletonKingEntity.class,
                    net.minecraft.world.entity.ai.targeting.TargetingConditions.forNonCombat().range(32),
                    mob, mob.getX(), mob.getY(), mob.getZ(), mob.getBoundingBox().inflate(32));
        }
        if (king == null || !king.isAlive()) return false;
        double distSq = mob.distanceToSqr(king);
        return distSq > maxDistance * maxDistance;
    }

    @Override
    public boolean canContinueToUse() {
        if (king == null || !king.isAlive()) return false;
        double distSq = mob.distanceToSqr(king);
        return distSq > minDistance * minDistance;
    }

    @Override
    public void start() {
        mob.getNavigation().moveTo(king, speedModifier);
    }

    @Override
    public void tick() {
        if (king != null && king.isAlive()) {
            mob.getNavigation().moveTo(king, speedModifier);
        }
    }

    @Override
    public void stop() {
        mob.getNavigation().stop();
    }
}