import { EntityComponentTypes, ItemStack, system, world } from "@minecraft/server";
import { hasItems } from "../utils/utils";

const guidebookId = "pixell_bbo:guidebook";

const pageAmount = 5;

world.afterEvents.dataDrivenEntityTrigger.subscribe((event) => {
    const { entity, eventId } = event;

    if (entity.typeId == guidebookId) {
        const pageProperyId = "book:page";

        const currentPage = entity.getProperty("book:page");

        switch (eventId) {
            case "book:nextpage": {
                entity.playAnimation("animation.pixell_bbo.guidebook.slide_left");

                entity.dimension.playSound("entity.book.page", entity.location);

                system.runTimeout(() => {
                    currentPage < pageAmount - 1
                        ? entity?.setProperty(pageProperyId, currentPage + 1)
                        : entity?.setProperty(pageProperyId, 0);
                }, 0.3 * 20);

                break;
            }

            case "book:previouspage": {
                entity.playAnimation("animation.pixell_bbo.guidebook.slide_right");

                entity.dimension.playSound("entity.book.page", entity.location);

                system.runTimeout(() => {
                    currentPage == 0
                        ? entity.setProperty(pageProperyId, pageAmount - 1)
                        : entity.setProperty(pageProperyId, currentPage - 1);
                }, 0.3 * 20);

                break;
            }

            case "book:despawn": {
                entity.triggerEvent("book:drop_timer");

                break;
            }

            case "minecraft:entity_spawned": {
                entity.dimension.playSound("entity.book.page", entity.location);

                break;
            }
        }
    }
});

function fetchPlayers() {
    for (let player of world.getAllPlayers()) {
        if (!player.hasTag(guidebookId)) {
            const inventoryComponent = player.getComponent(EntityComponentTypes.Inventory);

            if (!inventoryComponent) return;
            const guidebookItem = new ItemStack(`${guidebookId}_spawn_egg`, 1);

            const hasGuidebook = hasItems(player, `${guidebookId}_spawn_egg`);

            if (hasGuidebook) return;

            inventoryComponent.container.addItem(guidebookItem);

            player.addTag(guidebookId);
        }
    }
}

world.afterEvents.playerJoin.subscribe((e) => system.runTimeout(() => fetchPlayers(), 20));

world.afterEvents.worldInitialize.subscribe((e) => system.runTimeout(() => fetchPlayers(), 20));

system.runTimeout(() => fetchPlayers(), 5);

system.runTimeout(() => fetchPlayers(), 10);

system.runTimeout(() => fetchPlayers(), 20);

system.runInterval(() => fetchPlayers(), 60);
