import { world } from "@minecraft/server";
import { ActionFormData } from "@minecraft/server-ui";
class GuideBookMng {
    constructor() {
        this.guideBooks = new Map();
        world.afterEvents.itemUse.subscribe(({ source, itemStack }) => {
            if (this.guideBooks.has(itemStack.typeId)) {
                const bookData = this.guideBooks.get(itemStack.typeId);
                const defaultPage = bookData.default;
                const pagesData = bookData.pages;
                this.openPage(pagesData, defaultPage, source);
            }
        });
    }
    //注册
    addGuideBook(itemId, guideBook) {
        this.guideBooks.set(itemId, guideBook);
    }
    openPage(pagesData, page, source) {
        const pageForm = new ActionFormData();
        const pageData = pagesData[page];
        let buttons = [];
        let events = [];
        let texts = { rawtext: [] };
        pageForm.title({ translate: pageData.title });
        for (const i of pageData.body) {
            texts.rawtext?.push({ translate: i }, { text: '§f§r\n' });
        }
        pageForm.body(texts);
        for (const i of pageData.buttons) {
            pageForm.button(i.text, i.icon);
            if (i.jump_to) {
                buttons.push(i.jump_to);
            }
            else {
                buttons.push(undefined);
            }
            if (i.event) {
                events.push(i.event);
            }
            else {
                events.push(undefined);
            }
        }
        pageForm.show(source).then((response) => {
            if (response.selection === undefined)
                return;
            const page = buttons[response.selection];
            const event = events[response.selection];
            source.playSound("item.book.page_turn", { pitch: 1.0, volume: 5.0, });
            if (page) {
                this.openPage(pagesData, page, source);
            }
            if (event) {
                source.runCommand(`scriptevent ${event.identifer} ${event.data}`);
            }
        });
    }
}
export const guideBookMng = new GuideBookMng();
