import { EntityInitializationCause, EntitySkinIdComponent, GameMode, ItemCooldownComponent, system, world } from "@minecraft/server";
import { ActionFormData } from "@minecraft/server-ui";
import config from "nps_mot/config";
import { Buttons, calculateEuclideanDistance, getDimensionLocation, isInRange } from "nps_mot/utils/my_API";
import { parameterNames, Settings } from "nps_mot/utils/scoreboard";
world.beforeEvents.itemUse.subscribe(event => {
    useLeadCarrots(event);
});
world.afterEvents.entityHurt.subscribe(event => {
    mannequinRecovery(event);
    damageIndicator(event);
});
system.runInterval(() => {
    world.getAllPlayers().forEach(player => {
        player.runCommand('function nps/mot/hand_held_lantern');
    });
}, 2);
world.afterEvents.entitySpawn.subscribe((event) => {
    announceMerchantArrival(event);
});
world.beforeEvents.itemUseOn.subscribe(event => {
    const isTrainingMannequin = event.itemStack.typeId === `nps_mot:training_mannequin_spawn_egg`;
    const isMonsterSpawner = event.block.typeId === 'minecraft:mob_spawner';
    if (isTrainingMannequin && isMonsterSpawner) {
        event.cancel = true;
    }
});
function useLeadCarrots(event) {
    const itemStack = event.itemStack;
    if (itemStack.typeId !== "nps_mot:lead_carrot") {
        return;
    }
    event.cancel = true;
    system.run(() => {
        const player = event.source;
        const icc = itemStack.getComponent(ItemCooldownComponent.componentId);
        const cooldownTicksRemaining = icc.getCooldownTicksRemaining(player);
        if (cooldownTicksRemaining == 0) {
            icc.startCooldown(player);
            if (Settings.getValue(parameterNames.oreMerchantInvocation) == 1) {
                if (player.matches({ gameMode: GameMode.creative }) == false) {
                    player.runCommand('clear @s nps_mot:lead_carrot -1 1');
                }
                const blockFromView = player.getBlockFromViewDirection();
                let spawnLocation = player.location;
                if (blockFromView !== undefined) {
                    const distance = calculateEuclideanDistance(blockFromView.block.center(), player.location);
                    if (distance <= 4) {
                        spawnLocation = blockFromView.block.center();
                    }
                }
                player.playSound('nps_mot:sparkle_1', { location: spawnLocation });
                player.dimension.spawnParticle('nps_mot:apparition_1', spawnLocation);
                system.runTimeout(() => {
                    player.playSound('nps_mot:apparition_1', { location: spawnLocation });
                    player.dimension.spawnEntity('nps_mot:ore_merchant', spawnLocation);
                }, 120);
            }
            else {
                const disableMsg = `nps_mot:oreMerchantInvocationDisableMessage`;
                player.onScreenDisplay.setActionBar({ translate: disableMsg });
                player.runCommand('/playsound note.bass @s ~ ~ ~ 1 0.5');
            }
        }
        else {
            player.onScreenDisplay.setActionBar({ rawtext: [{ "translate": "nps_mot:peridot_amulet.active_cooldown" }] });
            player.runCommand('/playsound note.bass @s ~ ~ ~ 1 0.8');
        }
    });
}
function announceMerchantArrival(event) {
    if (event.entity.typeId !== `nps_mot:ore_merchant`) {
        return;
    }
    if (event.cause !== EntityInitializationCause.Spawned) {
        return;
    }
    world.getAllPlayers().forEach(player => {
        if (player.dimension.id === event.entity.dimension.id) {
            const distanceFromMerchant = calculateEuclideanDistance(player.location, event.entity.location);
            if (distanceFromMerchant <= 64) {
                player.sendMessage([config.addonPrefix, { translate: `nps_mot:arrivalOfTheMerchant` }]);
            }
        }
    });
}
function mannequinRecovery(event) {
    const training_mannequin_id = `nps_mot:training_mannequin`;
    if (event.hurtEntity.typeId != training_mannequin_id) {
        return;
    }
    if (event.damageSource.damagingEntity?.typeId !== "minecraft:player") {
        return;
    }
    const player = event.damageSource.damagingEntity;
    if (player.isSneaking == false) {
        return;
    }
    const training_mannequin = event.hurtEntity;
    showRecoveryConfirmationForm(player, training_mannequin);
}
function damageIndicator(event) {
    const damageIndicator = Settings.getValue(parameterNames.damageIndicators);
    if (damageIndicator == 0) {
        return;
    }
    //
    const hurtEntity = event.hurtEntity;
    if (!hurtEntity.isValid()) {
        return;
    }
    //
    const damage = event.damage;
    if (damage < 0) {
        return;
    }
    //
    spawnDamageIndicator(getDimensionLocation(hurtEntity), damage);
}
function spawnDamageIndicator(dimensionLocation, damage) {
    const DAMAGE_INDICATOR_TYPE_ID = `nps_mot:damage_indicator`;
    const y = dimensionLocation.y + 1.5;
    const inRange = isInRange(y, dimensionLocation.dimension.heightRange.min, dimensionLocation.dimension.heightRange.max);
    if (!inRange) {
        return;
    }
    const damage_indicator = dimensionLocation.dimension.spawnEntity(DAMAGE_INDICATOR_TYPE_ID, { x: dimensionLocation.x, y: y, z: dimensionLocation.z });
    let skin_id = damage_indicator.getComponent(EntitySkinIdComponent.componentId);
    skin_id.value = damage;
}
function showRecoveryConfirmationForm(player, mannequin) {
    system.run(() => {
        let form = new ActionFormData();
        form.title({ translate: 'nps_mot:training_mannequin.recover.title' });
        form.body({ translate: 'nps_mot:training_mannequin.recover.body' });
        form.button(Buttons.yes.rawtext, Buttons.yes.iconPath);
        form.button(Buttons.no.rawtext, Buttons.no.iconPath);
        form.show(player).then(response => {
            if (response.canceled) {
                return;
            }
            if (response.selection === 0) {
                recoverMannequin(player, mannequin);
            }
        });
    });
}
function recoverMannequin(player, mannequin) {
    if (player.matches({ gameMode: GameMode.survival }) || player.matches({ gameMode: GameMode.creative })) {
        mannequin.remove();
        player.runCommand(`give @s nps_mot:training_mannequin_spawn_egg`);
        player.sendMessage([config.addonPrefix, { translate: 'nps_mot:training_mannequin.recover.success' }]);
    }
    else {
        player.sendMessage([config.addonPrefix, { translate: 'nps_mot:training_mannequin.recover.fail' }]);
    }
}
