import {
    applyEnchant,
    enchantListToLore,
    bookApplicable,
    getCustomEnchants,
    setCustomEnchants
} from "cubc/mo_en/enchanthelpers";
import {bookInfo, lorePerBook} from "cubc/mo_en/enchantinfo"


// Sets the lore of all custom books in a players inventory
export function setBookLore(player) {
    const inventory = player.getComponent('minecraft:inventory').container;

    for (let i = 0; i < inventory.size; i++) {
        const item = inventory.getItem(i);
        if (item && item.typeId.includes("cubc_mo_en") && item.typeId.includes("book") && item.getLore().length === 0) {
            item.setLore(lorePerBook[item.typeId]);
            inventory.setItem(i, item);
        }
    }
}

// Applies a custom enchanting book to an item if this is possible.
export function applyBook(player, book_item, item) {
    if (!bookApplicable(book_item, item)) {
        console.warn(`Book ${book_item.typeId} not applicable to ${item.typeId}`);
        return false;
    }

    let enchantInfo = bookInfo[book_item.typeId];
    let currentItemEnchants = getCustomEnchants(item);
    let newEnchant = {
        "enchant": enchantInfo["enchantName"],
        "level": enchantInfo["level"]
    };

    // Update the item with the new enchants
    if (applyEnchant(player, currentItemEnchants, newEnchant, enchantInfo["maxLevel"])) {

        // Set the enchantment data
        setCustomEnchants(item, currentItemEnchants);
        item.setLore(enchantListToLore(currentItemEnchants));

        return true;
    } else {
        return false;
    }
}