import {
    world,
    system,
    ItemStack
} from "@minecraft/server";

import { getElement, getElementColour, getCost, getLore } from "./main.js"
import { sendNotification } from "main.js"

system.beforeEvents.startup.subscribe((event) => {
    event.itemComponentRegistry.registerCustomComponent("mm:mystery_scroll", {
        onUse(e) {
            const source = e.source;
            source.playSound("block.cartography_table.use", { pitch: 1.2 })
        },
        onCompleteUse(e, p) {
            var spellOptions = p.params.options;
            if (spellOptions == undefined || spellOptions.length == 0) spellOptions = []
            const source = e.source;
            const equippable = source.getComponent("minecraft:equippable")
            let newScroll = new ItemStack("mm:scroll", 1)
            if (spellOptions.length >= 1) {
                let rand = Math.floor(Math.random() * spellOptions.length);
                let spell = spellOptions[rand];
                newScroll.setLore([("§8§o" + getCost(spell, undefined, undefined) + " Mana§r"), getElementColour(getElement(spell)) + getLore(spell)])
                newScroll.setDynamicProperty("mm:spell", spell)

                if (!source.hasTag(spell + "_recipe_unlocked")) {
                    source.addTag(spell + "_recipe_unlocked")
                    sendNotification(source, `§dNew Recipe\n§r${getLore((spell))}`, "textures/ui/form/spell/spell_" + spell.replace("mm:", ""), getElement(spell))
                }
            }

            equippable.setEquipment("Mainhand", newScroll)
            source.dimension.spawnParticle("minecraft:witchspell_emitter", source.location)
            source.playSound("block.enchanting_table.use", { pitch: 0.5 })
            source.startItemCooldown("spell", 20);
        }
    })
})