import { EntitySpawnAfterEvent, world, Entity } from "@minecraft/server"

/**
 * @param {EntitySpawnAfterEvent} spawnEvent
 */
export const colliderSpawner = (spawnEvent) => {
    try {
        const entity = spawnEvent.entity;
        const dimension = entity.dimension;

        var i = 1;
        while (1) {
            try {
                const colliderEntity = dimension.spawnEntity(entity.typeId + "_collider" + i, entity.location);
                colliderEntity.setDynamicProperty("collider", entity.id);
            } catch {
                return
            }
        }
    } catch {

    }
}

/**
 * @param {Entity} colliderEntity
 */
export const colliderEntityTick = (colliderEntity) => {
    const collider = colliderEntity.getDynamicProperty("collider");
    const offsetX = colliderEntity.getProperty("af:collider.offset-x") ?? 0;
    const offsetY = colliderEntity.getProperty("af:collider.offset-y") ?? 0;
    const offsetZ = colliderEntity.getProperty("af:collider.offset-z") ?? 0;
    if (!collider) return;

    const entity = world.getEntity(collider);
    if (!entity) return;

    const entityRot = entity.getRotation();
    const entityPos = entity.location;

    const yawRad = GeneralUtils.math.toRad(entityRot.y);
    const pitchRad = GeneralUtils.math.toRad(entityRot.x);

    const yawCos = Math.cos(yawRad), yawSin = Math.sin(yawRad);
    const pitchCos = Math.cos(pitchRad), pitchSin = Math.sin(pitchRad);

    colliderEntity.teleport(
        {
            x: entityPos.x + offsetX * yawCos - offsetZ * yawSin,
            y: entityPos.y + offsetY * pitchCos - offsetZ * pitchSin,
            z: entityPos.z + offsetX * yawSin + offsetZ * yawCos
        },
        { rotation: entityRot }
    );

    colliderEntity.setRotation(entityRot);
}