import { world, system, Player, PlayerInputPermissions, ItemStack, EntityComponentTypes, EquipmentSlot } from "@minecraft/server";
import { ITEM_LORES, DEFAULT_ITEM_LORE } from "../data/lore.js";


export class MSPlayer {

    /**
     * Enables the input permissions of this player.
     *
     * @param {Player} player - Player.
    */
    static enableInputs(player) {
        const inputPermissions = player.inputPermissions;
        inputPermissions.cameraEnabled = true;
        inputPermissions.movementEnabled = true;
    }

    /**
     * Disables the input permissions of this player.
     *
     * @param {Player} player - Player.
    */
    static disableInputs(player) {
        const inputPermissions = player.inputPermissions;
        inputPermissions.cameraEnabled = false;
        inputPermissions.movementEnabled = false;
    }

}


export class ADPlayer {

    static #cycleItems = {
        "mythicus_tw:sort": ["mythicus_tw:sort.color", "mythicus_tw:sort.default", "mythicus_tw:sort.name"],
        "mythicus_tw:drawer.remote": ["mythicus_tw:drawer.remote", "mythicus_tw:drawer.remote.player"],
    };

    /**
     * Sets the lore for this player's item according to add-on settings and returns the reference to that item.
     *
     * @param {Player} player - Player.
     * @param {ItemStack} item - Item.
     * 
     * @returns {ItemStack} - Updated item.
    */
    static setItemLore(player, item) {
        const lore = (player.getDynamicProperty("mythicus_tw:addonSettings.advancedItemDescs") ?? true) ?
            ["", ...(ITEM_LORES[item.typeId] ?? [])] :
            [];
        item.setLore([...lore, "", ...DEFAULT_ITEM_LORE]);

        return item;
    }

    /**
     * Try to cycle this item.
     *
     * @param {Player} player - Player.
     * @param {ItemStack|String} item - Item stack or type id.
     * 
     * @returns {Boolean} - True if successfully cycled, false otherwise.
    */
    static cycleItem(player, item) {

        if (item instanceof ItemStack) item = item.typeId;

        let cycleItem;
        for (const cycle of Object.values(this.#cycleItems)) {
            const index = cycle.indexOf(item);
            if (index !== -1) {
                cycleItem = cycle[(index + 1) % cycle.length];
                break;
            }
        }

        if (!cycleItem) return false;

        try {
            const itemStack = this.setItemLore(player, new ItemStack(cycleItem));
            player.getComponent(EntityComponentTypes.Equippable).setEquipment(EquipmentSlot.Mainhand, itemStack);
        } catch {
            return false;
        }

        return true;
    }

}