import * as mc from "@minecraft/server";
import { getItemDinoDNAInfo, takeOneItem } from "../utilities";
import { dinoEgg, dinoList } from "../constants";
import { NAMESPACE } from "../anvilConstants";
function placeDinoEggInIncubator(player, itemStack) {
    player.getEntitiesFromViewDirection({ maxDistance: 6 }).forEach((entity) => {
        if (entity.entity.typeId === `${NAMESPACE}:incubator` && entity.entity.getProperty(`${NAMESPACE}:state`) === "empty") {
            takeOneItem(player, new mc.ItemStack(dinoEgg, 1));
            const dinoTypeID = getItemDinoDNAInfo(itemStack);
            entity.entity.triggerEvent("growing");
            entity.entity.setDynamicProperty(`${NAMESPACE}:dinosaur`, dinoTypeID);
            entity.entity.setProperty(`${NAMESPACE}:variant`, Object.keys(dinoList).indexOf(dinoTypeID));
        }
    });
}
export function dinoEggUseEvent(eventData) {
    const itemStack = eventData.itemStack;
    const user = eventData.source;
    if (itemStack.typeId === dinoEgg) {
        placeDinoEggInIncubator(user, itemStack);
    }
}
export function incubatorScriptEvent(eventData) {
    const id = eventData.id;
    const sourceEntity = eventData.sourceEntity;
    if (id === `${NAMESPACE}:incubator_stop` && sourceEntity && sourceEntity.typeId === `${NAMESPACE}:incubator`) {
        const dinoTypeID = sourceEntity.getDynamicProperty(`${NAMESPACE}:dinosaur`);
        const itemStack = new mc.ItemStack(`${NAMESPACE}:${dinoTypeID}_egg`, 1);
        const location = sourceEntity.location;
        let rotation = sourceEntity.getRotation();
        rotation.y = Math.round(rotation.y / 90) * 90;
        sourceEntity.dimension.spawnItem(itemStack, {
            x: location.x - 2 * Math.sin(rotation.y * Math.PI / 180),
            y: location.y,
            z: location.z + 2 * Math.cos(rotation.y * Math.PI / 180),
        });
        sourceEntity.clearDynamicProperties();
        sourceEntity.setProperty(`${NAMESPACE}:state`, "empty");
    }
}
