import { Block, Direction, Entity, EntityDamageCause, EquipmentSlot, ItemUseOnBeforeEvent, Player, system } from "@minecraft/server";
import { CustomBlockTags } from "../../blocks/utils/blockTags";
import { ItemHelper } from "../../items/utils/itemHelper";

export const GOLEM = {
    _typeId: "piki_beyondsurvival:golem",
    _deathEvent: "piki_beyondsurvival:death_event",
    _spawnEggId: "piki_beyondsurvival:golem_spawn_egg",


    isGolemKilledByCommand(typeId, cause) {
        return typeId == this._typeId && cause == EntityDamageCause.selfDestruct
    },

    isGolemSpawnEgg(itemTypeId) {
        return itemTypeId == this._spawnEggId
    },

    /**
     * 
     * @param {ItemUseOnBeforeEvent} ev 
     * @returns 
     */
    spawnGolem(ev) {
        const {block, blockFace, source} = ev;

        const sneakRequired = CustomBlockTags.isSneakRequired(block)
        const sneakRequiredOnSide = CustomBlockTags.isSneakRequiredOnSide(block)
        const isPlacingOnSide = blockFace != Direction.Down && blockFace != Direction.Up

        if (sneakRequired && !source.isSneaking) return
        if (sneakRequiredOnSide && !source.isSneaking && isPlacingOnSide) return

        ev.cancel = true

        // console.warn(`Golem spawn egg used at coordinates: x=${block.x}, y=${block.y}, z=${block.z}`);

        ItemHelper.clearPlayerItem(source, EquipmentSlot.Mainhand)
        system.run(() => {
            const entity = source.dimension.spawnEntity("piki_beyondsurvival:golem", block.location)
            entity.addTag("dont_despawn")
        })
    },

    /**
     * 
     * @param {Entity} golem 
     */
    onDeath(golem) {
        golem.triggerEvent(this._deathEvent)
    }
} 