/*
 * 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 net.minecraft.world.entity.LivingEntity;
import net.minecraft.world.entity.Mob;
import net.minecraft.world.entity.ai.goal.target.TargetGoal;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.phys.AABB;
import net.minecraft.world.scores.Team;

import java.util.EnumSet;
import java.util.List;

public class TeamHurtByTargetGoal extends TargetGoal {
    private final boolean alertSameTeam;
    private int timestamp;

    public TeamHurtByTargetGoal(Mob mob, boolean alertSameTeam) {
        super(mob, false, false);
        this.alertSameTeam = alertSameTeam;
        this.setFlags(EnumSet.of(Flag.TARGET));
    }

    @Override
    public boolean canUse() {
        int lastHurtBy = this.mob.getLastHurtByMobTimestamp();
        LivingEntity attacker = this.mob.getLastHurtByMob();
        if (attacker == null || attacker == this.mob) return false;
        if (lastHurtBy == this.timestamp) return false;
        if (!attacker.isAlive()) return false;
        // 排除创造模式玩家
        return !(attacker instanceof Player player) || !player.isCreative();
    }

    @Override
    public void start() {
        LivingEntity attacker = this.mob.getLastHurtByMob();
        if (attacker == null) return;

        this.mob.setTarget(attacker);
        this.timestamp = this.mob.getLastHurtByMobTimestamp();

        if (this.alertSameTeam) {
            double range = 32.0;
            AABB aabb = this.mob.getBoundingBox().inflate(range);
            List<Mob> list = this.mob.level().getEntitiesOfClass(Mob.class, aabb);
            Team team = this.mob.getTeam();
            if (team == null) return;

            for (Mob other : list) {
                if (other == this.mob) continue;
                if (other.getTeam() == team) {
                    // 检查目标是否是创造模式玩家
                    if (attacker instanceof Player player && player.isCreative()) continue;
                    other.setTarget(attacker);
                }
            }
        }
    }
}