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

const pagesAmount = 16;
const tempProperties = {};

const guidebookID = "ns_ma:guidebook_spawn_egg";

const guidebook = new ItemStack(guidebookID);

system.afterEvents.scriptEventReceive.subscribe((event) => {
    const { id, message, sourceType, sourceEntity } = event;

    if (message == "inkbook" && sourceEntity.isValid) {
        let delay = getTempProperty(sourceEntity.id, 0);
        let page = sourceEntity.getProperty("book:page");

        if (id == "ink_book:dead" && sourceEntity.isValid) {
            sourceEntity.dimension.spawnItem(guidebook, sourceEntity.location);

            sourceEntity.remove();
        } else if (delay + 25 < system.currentTick && sourceEntity.isValid) {
            setTempProperty(sourceEntity.id, system.currentTick);

            switch (id) {
                case "ink_book:nextpage":
                    if (page < pagesAmount) {
                        system.runTimeout(() => {
                            sourceEntity.setProperty(
                                "book:page",
                                page + 1 == pagesAmount ? pagesAmount : page + 1
                            );
                        }, 19);

                        sourceEntity.playAnimation("next");
                    }
                    break;
                case "ink_book:backpage":
                    if (page > 0) {
                        sourceEntity.playAnimation("back");
                        sourceEntity.setProperty("book:page", --page);
                    }
                    break;
            }
        }
    }
});

function getTempProperty(id, def) {
    tempProperties[id] = tempProperties[id] ?? def;

    return tempProperties[id];
}

function setTempProperty(id, def) {
    tempProperties[id] = def;
}

world.afterEvents.playerSpawn.subscribe((event) => {
    const { initialSpawn, player } = event;

    const started = player.getDynamicProperty("started");

    const inventory = player.getComponent("minecraft:inventory").container;

    const guidebook = new ItemStack("ns_ma:guidebook_spawn_egg");

    if (started == false || started == undefined) {
        player.setDynamicProperty("started", true);

        inventory.addItem(guidebook);
    }
});

world.afterEvents.itemUseOn.subscribe((event) => {
    const { itemStack, source: player } = event;

    const equipment = player.getComponent("minecraft:equippable");

    const heldItem = equipment.getEquipment(EquipmentSlot.Mainhand);

    if (itemStack?.typeId == guidebookID) {
        equipment.setEquipment(EquipmentSlot.Mainhand);
    }
});
