/*
    IMPORTANT: THAT IS A FILE AUTO GENERATED EVERY TIME WHEN YOU OPEN GUIDEBOOK EDITOR
               PLEASE DON'T CHANGE/EDIT THIS FILE ALL CONTENT WILL REPLACED EVERY TIME WHEN YOU
               OPEN THE EDITOR
*/

import { world } from "@minecraft/server"
import { ActionFormData } from "@minecraft/server-ui"
import * as data from "./data.js"
const content = data.default;
const pages = content.pages;

const processText = (text = '') => {
    const KEYS_AZ =
        'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789.:-_';
    /** @type {import("@minecraft/server").RawMessage} */
    const list = {rawtext: [{text: ''}]};

    let src = '';
    let key = false;

    for (let i = 0; i < text.length; i++) {
      const ch = text.charAt(i);
      if (ch == '#' && !key) {
        if (src.length > 0) {
          list.rawtext.push({text: src})
        }
        key = true;
        src = '';
      } else if (KEYS_AZ.indexOf(ch) == -1 && key) {
        key = false;
        list.rawtext.push({translate: `${src}`, with: ["\n"]});
        if (ch == '~')
          src = '';
        else
          src = '' + ch;
      } else {
        src = src + ch;
      }
    }
    if (src.length > 0) {
      if (key) {
        list.rawtext.push({translate: `${src}`, text: '' , with: ["\n"]})
      } else {
        list.rawtext.push({text: `${src}`})
      }
    }

    return list;
};

function showGuidebookPage(player, id) {
    if(!(id in pages)) {
        return;
    }
    
    const page = pages[id];
    const buttons = page.buttons ?? [];
    const form = new ActionFormData();
    
    const ids = [];

    form.title(processText(page.title.content));
    form.body(processText(page.body.content))
    /** [id, title, icon] */
    for(let button of buttons) {
        ids.push(button.destination)
        let iconPath = button.iconPath;
        while(iconPath && iconPath.startsWith("/")) {
          iconPath = iconPath.substring(1);
        }
        form.button(processText(button.text), iconPath)
    }
    form.show(player).then(res => {
        if(!res.canceled) {
            showGuidebookPage(player, ids[res.selection]);
        }
    });
}

world.afterEvents.itemUse.subscribe(e => {
    if(e.itemStack && e.itemStack.typeId == content.pack_id+":guidebook") {
        showGuidebookPage(e.source, content.home_page);
    }
});
