import { EntityInventoryComponent } from "@minecraft/server";

function getOrientation(playerRotationY) {
    switch (true) {
        case playerRotationY > 70 && playerRotationY < 170:
            return 4;
        case playerRotationY > -45 && playerRotationY < 65:
            return 1;
        case playerRotationY > -100 && playerRotationY < -10:
            return 3;
        case playerRotationY >= 148 || playerRotationY < -100:
            return 2
    }
}

function getOrientationX(playerRotationX) {
    switch (true) {
        case playerRotationX > 20 && playerRotationX < -20:
            return -1
        case playerRotationX > 37:
            return 1
        case playerRotationX < -21:
            return 0
        default:
            return -1
    }
}

function detectItemOnInventory(player, itemTypeId) {
    const playerInventoryComponentContainer = player.getComponent(EntityInventoryComponent.componentId).container;

    for (let i = 0; i < playerInventoryComponentContainer.size; i++) {
        const item = playerInventoryComponentContainer.getItem(i);

        if (!item) continue;
        if (item.typeId == itemTypeId) return { item, slot: i };
    }
}

function hasTag(itemStack, tag, tagRegexp = null) {
    return itemStack
        .getTags()
        .find(itemTag => tagRegexp ? tagRegexp.test(itemTag) : itemTag == tag);
}

function getRandomItem(array) {
    if (!array || array.length === 0) return;

    const randomIndex = Math.floor(Math.random() * array.length);
    return array[randomIndex];
}


export {
    getOrientation,
    getOrientationX,
    detectItemOnInventory,
    getRandomItem,
    hasTag
}