import { EntityComponentTypes, system, world } from "@minecraft/server";
import { allDirections, offsetPos } from "../util/dirUtils";
import { McBlocks } from "../reg/mcBlocks";
import { shrinkIfInSurvival } from "../util/miscUtils";
import { McEntities } from "../reg/mcEntities";
import { fallingBlocksManager } from "../fallingBlocksManager";
import { suppEvents } from "../suppEventHandler";
import { worldProxy } from "../worldProxy";
import { SuppParticles } from "../reg/suppParticles";
function tryDissolve(block) {
    let waterAround = 0;
    let dissolve = false;
    if (worldProxy.hasRainAt(block)) {
        dissolve = true;
    }
    for (const dir of allDirections) {
        const target = offsetPos(block, dir);
        if (target && (target.typeId == McBlocks.Water || target.isWaterlogged)) {
            waterAround++;
        }
        else if (target && target.typeId == McBlocks.FlowingWater) {
            dissolve = true;
        }
    }
    const center = block.center();
    if (waterAround >= 2) {
        block.dimension.setBlockType(block.location, McBlocks.Water);
        dissolve = true;
    }
    else if (waterAround != 0 || dissolve) {
        block.dimension.setBlockType(block.location, McBlocks.Air);
        dissolve = true;
    }
    if (dissolve) {
        block.dimension.spawnParticle(SuppParticles.BreakingSugar, center);
        suppEvents.fireOnBlockBroken(block);
    }
}
export const SugarBlockComponent = {
    onPlace(event) {
        tryDissolve(event.block);
    },
    onRandomTick(event) {
        tryDissolve(event.block);
    }
};
//need to use event because of the item model...
world.beforeEvents.itemUse.subscribe((event) => {
    const itemStack = event.itemStack;
    if (!itemStack || itemStack.typeId != "razz_sup:sugar_cube" /* SuppBlocks.SugarBlock */)
        return;
    //give speed to horse mount
    const player = event.source;
    //get mount
    const mount = player.getComponent(EntityComponentTypes.Riding);
    if (mount && (mount.entityRidingOn.typeId == McEntities.Horse || mount.entityRidingOn.typeId == McEntities.Mule || mount.entityRidingOn.typeId == McEntities.Donkey)) {
        //give speed effect
        const existing = mount.entityRidingOn.getEffect("minecraft:speed" /* McEffects.Swiftness */);
        const dur = 6 * 20;
        if (!existing || (existing.duration < dur && existing.amplifier <= 0)) {
            event.cancel = true; //cancel item use
            system.run(() => {
                mount.entityRidingOn.addEffect("minecraft:speed" /* McEffects.Swiftness */, dur);
                player.dimension.playSound("mob.horse.eat", mount.entityRidingOn.location);
                shrinkIfInSurvival(player, itemStack);
            });
        }
    }
});
fallingBlocksManager.register("razz_sup:sugar_cube" /* SuppBlocks.SugarBlock */, {});
