import * as mc from "@minecraft/server";
import { getItemDinoDNAInfo, setItemDinoDNALore, takeOneItem } from "../utilities";
import { dinoList, dnaExtract, amber } from "../constants";
import { NAMESPACE } from "../anvilConstants";
function placeDNAInAmberConverter(player, itemStack) {
    player.getEntitiesFromViewDirection({ maxDistance: 6 }).forEach((entity) => {
        if (entity.entity.typeId === `${NAMESPACE}:amber_converter` && entity.entity.getProperty(`${NAMESPACE}:state`) === "egg") {
            takeOneItem(player, itemStack);
            entity.entity.triggerEvent("growing");
            entity.entity.setDynamicProperty(`${NAMESPACE}:dinosaur`, getItemDinoDNAInfo(itemStack));
        }
    });
}
export function dnaExtractUseEvent(eventData) {
    const itemStack = eventData.itemStack;
    const user = eventData.source;
    if (itemStack.typeId === dnaExtract || itemStack.typeId === amber) {
        placeDNAInAmberConverter(user, itemStack);
    }
}
export function amberConverterScriptEvent(eventData) {
    const id = eventData.id;
    const sourceEntity = eventData.sourceEntity;
    if (id === `${NAMESPACE}:amber_converter_stop` && sourceEntity && sourceEntity.typeId === `${NAMESPACE}:amber_converter`) {
        const dinoTypeID = sourceEntity.getDynamicProperty(`${NAMESPACE}:dinosaur`);
        if (!dinoList[dinoTypeID]) {
            sourceEntity.clearDynamicProperties();
            sourceEntity.setProperty(`${NAMESPACE}:state`, "amber");
            sourceEntity.runCommand(`titleraw @a[r=8] actionbar ${JSON.stringify({ rawtext: [{ translate: `${NAMESPACE}.no_dna_found` }] })}`);
            return;
        }
        const dinoName = dinoList[dinoTypeID].name;
        const itemStack = setItemDinoDNALore(`${NAMESPACE}:dino_egg`, dinoName);
        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`, "amber");
    }
}