import { EnchantmentType, EquipmentSlot, ItemStack, world } from "@minecraft/server";
export class InventoryManager {
    source;
    inventory;
    equipment;
    constructor(source) {
        this.source = source;
        this.inventory = source.getComponent('minecraft:inventory');
        this.equipment = source.getComponent('minecraft:equippable');
    }
    managerInventory = {
        addItem: (itemStack) => {
            const container = this.inventory.container;
            if (container) {
                container.addItem(itemStack);
            }
        },
        getEquipment: (slot) => {
            return this.equipment.getEquipment(slot);
        },
        getEquipments: () => {
            const equipments = {
                mainHand: this.equipment.getEquipment(EquipmentSlot.Mainhand),
                offHand: this.equipment.getEquipment(EquipmentSlot.Offhand),
                head: this.equipment.getEquipment(EquipmentSlot.Head),
                chest: this.equipment.getEquipment(EquipmentSlot.Chest),
                legs: this.equipment.getEquipment(EquipmentSlot.Legs),
                feet: this.equipment.getEquipment(EquipmentSlot.Feet)
            };
            return equipments;
        },
        removeItem: (typeId, amount) => {
            const container = this.inventory.container;
            if (!container)
                return;
            for (let i = 0; i < this.inventory.inventorySize; i++) {
                const itemStack = container.getItem(i);
                if (itemStack.typeId === typeId) {
                    if (itemStack.amount > amount) {
                        itemStack.amount -= amount;
                        container.setItem(i, itemStack);
                        break;
                    }
                    else {
                        container.setItem(i);
                        break;
                    }
                }
            }
        },
        replaceItem: (tileName, replaceTileName) => {
            const container = this.inventory.container;
            if (!container)
                return;
            for (let i = 0; i < this.inventory.inventorySize; i++) {
                const itemStack = container.getItem(i);
                if (itemStack.typeId === replaceTileName) {
                    container.setItem(i, new ItemStack(tileName, 0));
                }
            }
        },
        removeEquipment: (slot) => {
            this.equipment.setEquipment(slot);
        },
        setEquipment: (itemStack, slot) => {
            this.equipment.setEquipment(slot, itemStack);
        },
        setItem: (itemStack, slot) => {
            const container = this.inventory.container;
            if (!container)
                return;
            if (itemStack == null) {
                container.setItem(slot);
                return;
            }
            container.setItem(slot, itemStack);
        },
        saveInventory: () => {
            const container = this.inventory.container;
            if (!container)
                return;
            const items = [];
            for (let i = 0; i < this.inventory.inventorySize; i++) {
                const itemStack = container.getItem(i);
                if (!itemStack)
                    continue;
                let itemData = {
                    typeId: itemStack.typeId,
                    amount: itemStack.amount
                };
                const durability = itemStack.getComponent("minecraft:durability");
                if (durability) {
                    itemData.durability = {
                        damage: durability.damage,
                        maxDurability: durability.maxDurability
                    };
                }
                const enchantable = itemStack.getComponent("minecraft:enchantable");
                const enchantments = [];
                enchantable?.getEnchantments().forEach((ench) => {
                    world.sendMessage(`Enchantments: ${ench.type.id} - Level: ${ench.level}`);
                    let enchantment = {
                        type: {
                            id: ench.type.id,
                            maxLevel: ench.type.maxLevel,
                        },
                        level: ench.level
                    };
                    enchantments.push(enchantment);
                });
                if (enchantable) {
                    itemData.enchantable = {
                        enchantments: enchantments,
                    };
                }
                const lore = itemStack.getLore();
                if (lore && lore.length > 0) {
                    itemData.lore = lore;
                }
                const customName = itemStack.nameTag;
                if (customName) {
                    itemData.nameTag = customName;
                }
                items.push(itemData);
            }
            world.sendMessage(`${objectToShortId(items)} | ${items.length} items saved.`);
            this.source.setDynamicProperty('nf_az:inventory', objectToShortId(items));
        },
        loadInventory: () => {
            const encoded = this.source.getDynamicProperty('nf_az:inventory');
            if (!encoded)
                return;
            const itemsRaw = shortIdToObject(encoded);
            const container = this.inventory.container;
            if (!container)
                return;
            itemsRaw.forEach((itemRaw, index) => {
                if (index < this.inventory.inventorySize) {
                    const itemStack = new ItemStack(itemRaw.typeId, itemRaw.amount);
                    if (itemRaw.durability) {
                        const durability = itemStack.getComponent("minecraft:durability");
                        if (durability) {
                            durability.damage = itemRaw.durability.damage;
                        }
                    }
                    if (itemRaw.enchantable && itemRaw.enchantable.enchantments) {
                        const enchantable = itemStack.getComponent("minecraft:enchantable");
                        if (enchantable) {
                            for (const ench of itemRaw.enchantable.enchantments) {
                                try {
                                    const enchantmentType = new EnchantmentType(ench.type.id);
                                    const enchantment = { level: ench.level, type: enchantmentType };
                                    enchantable.addEnchantment(enchantment);
                                }
                                catch (e) {
                                    console.warn(`Falha ao adicionar encantamento: ${JSON.stringify(ench)}`, e);
                                }
                            }
                        }
                    }
                    if (itemRaw.lore) {
                        itemStack.setLore(itemRaw.lore);
                    }
                    if (itemRaw.nameTag) {
                        itemStack.nameTag = itemRaw.nameTag;
                    }
                    container.setItem(index, itemStack);
                }
                else {
                    console.warn(`Item at index ${index} exceeds inventory size.`);
                }
            });
        }
    };
}
function btoa(str) {
    return base64Encode(str);
}
function atob(str) {
    return base64Decode(str);
}
const base64abc = [
    ...'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
];
function base64Encode(str) {
    let result = '', i = 0, l = str.length;
    for (; i < l; i += 3) {
        let a = str.charCodeAt(i);
        let b = str.charCodeAt(i + 1);
        let c = str.charCodeAt(i + 2);
        result += base64abc[a >> 2];
        result += base64abc[((a & 3) << 4) | (b >> 4)];
        result += isNaN(b) ? '=' : base64abc[((b & 15) << 2) | (c >> 6)];
        result += isNaN(c) ? '=' : base64abc[c & 63];
    }
    return result;
}
function base64Decode(str) {
    let result = '', i = 0, l = str.length;
    let bytes = [];
    for (; i < l; i += 4) {
        let a = base64abc.indexOf(str[i]);
        let b = base64abc.indexOf(str[i + 1]);
        let c = base64abc.indexOf(str[i + 2]);
        let d = base64abc.indexOf(str[i + 3]);
        bytes[0] = (a << 2) | (b >> 4);
        bytes[1] = ((b & 15) << 4) | (c >> 2);
        bytes[2] = ((c & 3) << 6) | d;
        result += String.fromCharCode(bytes[0]);
        if (c !== 64 && str[i + 2] !== '=')
            result += String.fromCharCode(bytes[1]);
        if (d !== 64 && str[i + 3] !== '=')
            result += String.fromCharCode(bytes[2]);
    }
    return result;
}
// Escape/unescape puro
function escape(str) {
    return str.replace(/[^*+.-9A-Z_a-z-]/g, function (c) {
        const hex = c.charCodeAt(0).toString(16).toUpperCase();
        return '%' + (hex.length < 2 ? '0' : '') + hex;
    });
}
function unescape(str) {
    return str.replace(/%([0-9A-Fa-f]{2})/g, function (_, hex) {
        return String.fromCharCode(parseInt(hex, 16));
    });
}
function objectToShortId(obj) {
    const json = JSON.stringify(obj);
    return btoa(unescape(encodeURIComponent(json)));
}
function shortIdToObject(id) {
    const json = decodeURIComponent(escape(atob(id)));
    return JSON.parse(json);
}
