import { system, EntityDamageCause, EntityRideableComponent, Player } from "@minecraft/server";
import { entityDamageConfig } from "../DATA/DamageConfig";
import { mountsFlying } from "./Flying";
const lastAttackTime = new Map();
const cockatriceAttackAreas = new Map();
let globalDamageIntervalId = undefined;
function getSuitableRaycastLocation(sourceEntity) {
    try {
        let viewDir = sourceEntity.getViewDirection();
        const mag = Math.sqrt(viewDir.x * viewDir.x + viewDir.y * viewDir.y + viewDir.z * viewDir.z);
        let normDir = { x: 0, y: 0, z: 0 };
        if (mag !== 0) {
            normDir = { x: viewDir.x / mag, y: viewDir.y / mag, z: viewDir.z / mag };
        }
        const fallbackDistance = !isMountFlying(sourceEntity) ? 4.5 : 10;
        let targetLocation = {
            x: sourceEntity.location.x + normDir.x * fallbackDistance,
            y: sourceEntity.location.y + normDir.y * fallbackDistance,
            z: sourceEntity.location.z + normDir.z * fallbackDistance,
        };
        const stepDown = 0.5;
        while (targetLocation.y > 0) {
            const block = sourceEntity.dimension.getBlock(targetLocation);
            if (block && !block.isAir) {
                break;
            }
            targetLocation.y -= stepDown;
        }
        return targetLocation;
    }
    catch {
        return;
    }
}
function startGlobalDamageInterval(cockatriceConfig) {
    try {
        const cockatrice = cockatriceConfig.cockatrice;
        if (cockatriceConfig && cockatrice) {
            if (globalDamageIntervalId !== undefined)
                return;
            globalDamageIntervalId = system.runInterval(() => {
                const currentTime = Date.now();
                const attackIds = Array.from(cockatriceAttackAreas.keys());
                for (let i = 0; i < attackIds.length; i++) {
                    const id = attackIds[i];
                    const attackInstance = cockatriceAttackAreas.get(id);
                    if (!attackInstance)
                        continue;
                    const elapsed = currentTime - attackInstance.startTime;
                    if (elapsed >= cockatrice.effectDuration * 1000) {
                        cockatriceAttackAreas.delete(id);
                        continue;
                    }
                    const damage = cockatriceConfig.skillDamage;
                    const affectedEntities = attackInstance.source.dimension.getEntities({
                        location: attackInstance.location,
                        maxDistance: cockatriceConfig.skillAttackRadius,
                        excludeTypes: ["minecraft:item", "minecraft:xp_orb"],
                    });
                    for (let j = 0; j < affectedEntities.length; j++) {
                        const ent = affectedEntities[j];
                        if (ent.id === attackInstance.source.id)
                            continue;
                        let skipDamage = false;
                        const sourceRideable = attackInstance.source.getComponent(EntityRideableComponent.componentId);
                        if (sourceRideable) {
                            const riders = sourceRideable.getRiders();
                            for (let k = 0; k < riders.length; k++) {
                                if (riders[k].id === ent.id) {
                                    skipDamage = true;
                                    break;
                                }
                            }
                        }
                        if (!skipDamage) {
                            try {
                                ent.applyDamage(damage, { cause: EntityDamageCause.magic });
                                ent.addEffect("slowness", cockatrice.effectDuration, {
                                    amplifier: cockatrice.effectAmplifier,
                                    showParticles: false,
                                });
                            }
                            catch (e) { }
                        }
                    }
                }
                if (cockatriceAttackAreas.size === 0 && globalDamageIntervalId !== undefined) {
                    stopGlobalDamageInterval();
                }
            }, cockatrice.damageInterval);
        }
    }
    catch { }
}
function stopGlobalDamageInterval() {
    try {
        if (globalDamageIntervalId !== undefined) {
            system.clearRun(globalDamageIntervalId);
            globalDamageIntervalId = undefined;
        }
    }
    catch { }
}
export function cockatriceGasAttack(sourceEntity, _log) {
    try {
        const cockatriceConfig = entityDamageConfig[sourceEntity.typeId];
        const cockatrice = cockatriceConfig.cockatrice;
        if (cockatriceConfig && cockatrice) {
            playCockAtriceAnimation(sourceEntity);
            const now = Date.now();
            const lastTime = lastAttackTime.get(sourceEntity.id) || 0;
            if (now - lastTime < (cockatrice.effectCooldown ?? 0))
                return;
            lastAttackTime.set(sourceEntity.id, now);
            const targetLocation = getSuitableRaycastLocation(sourceEntity);
            if (!targetLocation) {
                return;
            }
            system.runTimeout(() => {
                const attackId = sourceEntity.id + "-" + Date.now();
                const startTime = Date.now();
                cockatriceAttackAreas.set(attackId, {
                    location: targetLocation,
                    startTime: startTime,
                    source: sourceEntity,
                });
                try {
                    if (cockatrice.particleGas) {
                        const particleId = sourceEntity.typeId === "kicu_mmad:spectral_cockatrice"
                            ? cockatrice.particleGas + "_g"
                            : cockatrice.particleGas;
                        sourceEntity.dimension.spawnParticle(particleId, targetLocation);
                    }
                }
                catch (e) { }
                startGlobalDamageInterval(cockatriceConfig);
            }, cockatrice.effectDelay);
        }
    }
    catch { }
}
function isMountFlying(entity) {
    try {
        const flyingState = entity.getProperty("kicu_mmad:flying");
        return flyingState !== undefined && flyingState !== 0;
    }
    catch {
        return false;
    }
}
function playCockAtriceAnimation(entity) {
    try {
        const config = entityDamageConfig[entity.typeId];
        const cockatrice = config.cockatrice;
        entity.runCommand(`playanimation @s ${mountsFlying[entity.id] === 0 ? config.noFlyShoot : config.flyShoot}`);
        if (config) {
            const now = Date.now();
            const lastTime = lastAttackTime.get(entity.id) || 0;
            const remainingCooldown = (cockatrice.effectCooldown ?? 0 - (now - lastTime)) / 1000;
            const isCooldown = remainingCooldown > 0;
            if (isCooldown && remainingCooldown >= 0.25) {
                const cooldownTimeInSeconds = remainingCooldown.toFixed(1);
                const sourceRideable = entity.getComponent(EntityRideableComponent.componentId);
                if (sourceRideable) {
                    const riders = sourceRideable.getRiders();
                    for (let k = 0; k < riders.length; k++) {
                        const player = riders[k];
                        if (player instanceof Player) {
                            player.onScreenDisplay.setActionBar({
                                rawtext: [{ translate: "dialog.kicu_mmad.cockatricetimer", with: [`\n`, `${cooldownTimeInSeconds}s`] }],
                            });
                            break;
                        }
                    }
                }
            }
        }
    }
    catch { }
}

//# sourceMappingURL=../../../../../_KiCuMountsBPDebug/kicu/mmad/C/CockatriceAttack.js.map
