import { ItemStack, Player, EquipmentSlot, GameMode, system } from "@minecraft/server";
import { CommandHelper as CHelper } from "../../utils/commandHelper";
import { EntityComponents as EComponents } from "../../entities/utils/entityComponents";
import { ItemTypeIds } from "./itemConstants";

export class ItemHelper {
    /**
     * 
     * @param {Player} source 
     * @param {number} amount
     * @param {EquipmentSlot} equipmentSlot 
     * @param {string} itemStackId
     */
    static clearPlayerItem(source, equipmentSlot = null, amount = 1, itemStackId = null, checkGameMode = true) {
        if (checkGameMode && source.getGameMode() == GameMode.creative) return
        
        if (!equipmentSlot && itemStackId) {
            const command = CHelper.generateClearCommand(itemStackId)
            source.runCommand(command)
            return
        }
        system.run(() => {
            const equippable = EComponents.getEquippable(source)
            const itemStack = equippable.getEquipment(equipmentSlot)
            if (itemStack.typeId == ItemTypeIds.waterBucket) {
                const bucketItem = new ItemStack(ItemTypeIds.bucket, 1)
                ItemHelper.clearPlayerItem(source, null, 1, itemStackId = ItemTypeIds.waterBucket)
                EComponents.getInventory(source).container.addItem(bucketItem)
            } else {
                if (itemStack.amount <= amount) equippable.setEquipment(equipmentSlot, new ItemStack(ItemTypeIds.air))
                else {
                    itemStack.amount -= amount
                    equippable.setEquipment(equipmentSlot, itemStack)
                }
            }
        })
    }


    /**
     * Gets the tag of a tool that starts with `minecraft:is_` then return the rest
     * @example Tag `minecraft:is_pickaxe` returns `pickaxe`
     * @param {ItemStack} itemStack 
     * @param {string} tagPrefix 
     * @returns {string} Supported return values are `pickaxe`, `axe`, `shovel`, `hoe`, `sword`
     */
    static getItemToolTier(itemStack) {
        if (!itemStack) return
        const possibleTiers = ["pickaxe", "axe", "shovel", "hoe", "sword"]
        for (const tag of itemStack?.getTags()) {
            for (const tier of possibleTiers) {
                if ("minecraft:is_" + tier == tag) return tier
            }
        }
        return undefined
    }
}