import { ContainerSlot, Entity, EntityEquippableComponent, EntityInventoryComponent, EntityTypeFamilyComponent, ItemStack } from "@minecraft/server";

export class EntityUtils {
    /** 
 * @param {Entity} entity
 * @returns {ItemStack} 
 */
    static getHandItem(entity) {
        /** @type {EntityEquippableComponent} */
        const component = entity.getComponent(EntityEquippableComponent.componentId);
        return component.getEquipment(EquipmentSlot.Mainhand) ?? new ItemStack("minecraft:air", 1);
    }

    /**
     * @param {Entity} entity 
     */
    static hasFamily(entity, family) {
        const familyComponent = entity.getComponent(EntityTypeFamilyComponent.componentId);
        if (familyComponent) {
            return familyComponent.hasTypeFamily(family);
        }
        return false;
    }
    /** @returns {ContainerSlot[] | undefined} */
    static getInventoryItems(entity) {
        const container = entity.getComponent("inventory")?.container;
        if (container) {
            const slots = []
            for (let i = 0; i < container.size; i++) {
                const slot = container.getSlot(i)
                if (slot && slot.hasItem()) {
                    slots.push(slot)
                }
            }
            return slots;
        }
        return undefined;
    }
    /**
 * 
 * @param {mc.ContainerSlot} slot 
 * @param {string} mode 
 * @param {number} value
 */
    static operateSlot(entity, slot, mode, value) {
        const container = entity.getComponent("inventory")?.container;
        if (typeof (slot) == "number") {
            slot = container.getSlot(slot)
        }
        const item = slot.getItem().clone()
        if (mode == "+") {
            var nextValue = item.amount + value
            item.amount = nextValue < item.maxAmount ? nextValue : item.amount
            slot.setItem(item)

        } else if (mode == "-") {
            var nextValue = item.amount - value
            item.amount = nextValue > 0 ? nextValue : 1
            slot.setItem(nextValue <= 0 ? undefined : item)
        }
        return slot
    }
    static hasItems(entity, id, count = 1) {
        /** @type {EntityInventoryComponent} */
        const inventory = entity.getComponent(EntityInventoryComponent.componentId);
        let amount = count;

        for (let i = 0; i < inventory.inventorySize; i++) {
            const item = inventory.container.getItem(i);
            if (item && item.typeId == id) {
                amount -= item.amount;
                if (amount <= 0) return true;
            }
        }

        return amount <= 0;
    }
}