import "cubc/mo_en/enchantsystem"
import "cubc/mo_en/applyenchants"
import "cubc/mo_en/book"
import {ItemStack, system, world} from "@minecraft/server"
import {applyBook} from "cubc/mo_en/enchants"
import {openAnvilMenu} from "cubc/mo_en/anvilmenu"
import {openEnchantMenu} from "cubc/mo_en/enchantmenu"

function get_integer(str) {
    return parseInt(str.replace(/\D/g, ""));
}

// Subscribe to function events
system.afterEvents.scriptEventReceive.subscribe((event) => {
    const {id, message, sourceEntity, sourceType} = event;
    let dimension = null;
    try {
        dimension = sourceEntity.dimension;
    } catch (e) {
        return;
    }

    if (id === "cubc_mo_en:delay") {
        let delay = parseInt(message.split('/')[0], 10);
        let command = message.split('/').slice(1).join('/');

        system.runTimeout(() => {
            try {
                sourceEntity.runCommand(command);
            } catch {
            }
        }, delay);
    }

    if (id === "cubc_mo_en:kill_items") {
        const {x: x, y: y, z: z} = sourceEntity.location;
        const dimension = sourceEntity.dimension;
        const r = get_integer(message);

        dimension.runCommand(`execute as @r positioned ${x} ${y} ${z} run kill @e[type=item, r=${r}]`);
        system.runTimeout(() => {
            dimension.runCommand(`execute as @r positioned ${x} ${y} ${z} run kill @e[type=item, r=${r}]`);
        }, 1);
    }

    if (id === "cubc_mo_en:repeat") {
        let data = message.split('/')[0];
        let command = message.split('/').slice(1).join('/');

        let repeat = get_integer(data.split(',')[0]);
        let delay = get_integer(data.split(',')[1]);

        for (let i = 0; i < repeat; i++) {
            system.runTimeout(() => {
                sourceEntity.runCommand(command);
            }, i * delay);
        }
    }

    if (id === "cubc_mo_en:force_enchant") {
        let book_item = new ItemStack(message);
        const equipment = sourceEntity.getComponent('equippable');
        const item = equipment.getEquipment('Mainhand');
        applyBook(sourceEntity, book_item, item);
        equipment.setEquipment('Mainhand', item);
    }
});

world.beforeEvents.worldInitialize.subscribe((initEvent) => {
    initEvent.blockComponentRegistry.registerCustomComponent("cubc_mo_en:anvil_click", {
        onPlayerInteract: (event) => {
            const {player, block, dimension, face, faceLocation} = event;
            openEnchantMenu(player);
        }
    });
});

world.beforeEvents.worldInitialize.subscribe((initEvent) => {
    initEvent.blockComponentRegistry.registerCustomComponent("cubc_mo_en:enchanting_table_click", {
        onPlayerInteract: (event) => {
            const {player, block, dimension, face, faceLocation} = event;
            openAnvilMenu(player);
        },
        onPlace: (event) => {
            const {block, dimension, previousBlock} = event;
            let {x: x, y: y, z: z} = block.location;
            dimension.spawnEntity("cubc_mo_en:display_book", {x: x + 0.5, y: y, z: z + 0.5});
        },
        onPlayerDestroy: (event) => {
            const {player, block, dimension, destroyedBlockPermutation} = event;
            let {x: x, y: y, z: z} = block.location;
            player.runCommand(`execute positioned ${x} ${y} ${z} run event entity @e[c=1, type=cubc_mo_en:display_book, r=1] cubc_mo_en:despawn`);
        }
    });
});