package me.earthme.luminol.mobaireducer;

import me.earthme.luminol.config.modules.optimizations.MobAiReducerConfig;
import net.minecraft.world.entity.PathfinderMob;
import net.minecraft.world.entity.ai.goal.Goal;
import net.minecraft.world.entity.ai.targeting.TargetingConditions;
import net.minecraft.world.entity.player.Player;
import net.minecraft.server.level.ServerLevel;

import java.util.EnumSet;

public class OptimizedTemptGoal extends Goal {

    private final MobAiReducerConfig module;
    private final PathfinderMob mob;
    private final TargetingConditions temptTargeting;
    private Player targetPlayer;
    private int cooldown = 0;

    public OptimizedTemptGoal(MobAiReducerConfig module, PathfinderMob mob, TargetingConditions temptTargeting) {
        this.module = module;
        this.mob = mob;
        this.temptTargeting = temptTargeting;
        this.setFlags(EnumSet.of(Flag.MOVE, Flag.LOOK));
    }

    @Override
    public boolean canUse() {
        if (cooldown-- > 0) return false;
        cooldown = 0;
        if (mob.level() instanceof ServerLevel serverLevel) {
            targetPlayer = serverLevel.getNearestPlayer(temptTargeting, mob);
        } else {
            targetPlayer = null;
        }
        return targetPlayer != null;
    }

    @Override
    public boolean canContinueToUse() {
        if (cooldown-- > 0) return true;
        cooldown = 0;
        return targetPlayer != null && targetPlayer.isAlive()
            && mob.distanceToSqr(targetPlayer) < module.temptRange * module.temptRange;
    }

    @Override
    public void stop() {
        targetPlayer = null;
        mob.getNavigation().stop();
        cooldown = 100;
    }

    @Override
    public void tick() {
        if (targetPlayer == null) return;
        mob.getLookControl().setLookAt(targetPlayer, 10.0f, (float) mob.getMaxHeadXRot());
        double dist = mob.distanceToSqr(targetPlayer);
        if (dist > 2.25) {
            mob.getNavigation().moveTo(targetPlayer, 1.0);
        } else {
            mob.getNavigation().stop();
        }
    }
}
