import { system } from "@minecraft/server";
import { ActionFormData } from "@minecraft/server-ui";

export const MENUS = [
  //// MAIN MENU
  {
    menuID: "pb_gat:bs_main",
    title: "§0Field Scanner",
    body: "§7Select a Biome To Locate:",
    buttons: [
      {
        title: "§0Plains",
        icon: "textures/pb/GaT/form_icons/biome_scanner/plains",
        connectID: "pb_gat:locate_plains",
      },
      {
        title: "§0Forest",
        icon: "textures/pb/GaT/form_icons/biome_scanner/forest",
        connectID: "pb_gat:locate_forest",
      },
      {
        title: "§0Exit",
        icon: "textures/pb/GaT/form_icons/exit_icon",
      },
    ],
    type: "form",
  },
  //// Biome locate confirm pages
  {
    menuID: "pb_gat:locate_plains",
    title: "§0Locate Plains",
    body: "§7Would you like to locate a 'Plains' biome?",
    buttons: [
      {
        title: "§0Yes",
        icon: "textures/pb/GaT/form_icons/yes_icon",
        callback: (player) => {
          locateBiome(player, "plains");
        },
      },
      {
        title: "§0Return",
        icon: "textures/pb/GaT/form_icons/return_icon",
        connectID: "pb_gat:bs_main",
      },
    ],
    type: "form",
  },
  {
    menuID: "pb_gat:locate_forest",
    title: "§0Locate Forest",
    body: "§7Would you like to locate a 'Forest' biome?",
    buttons: [
      {
        title: "§0Yes",
        icon: "textures/pb/GaT/form_icons/yes_icon",
        connectID: "pb_gat:forest",
      },
      {
        title: "§0Return",
        icon: "textures/pb/GaT/form_icons/return_icon",
        connectID: "pb_gat:bs_main",
      },
    ],
    type: "form",
  },
];

export function biomeScanner(player, item) {
  system.runTimeout(() => {
    openMenu(player, "pb_gat:bs_main");
  }, 1);
}

function openMenu(player, menuID) {
  const menu_data = MENUS.find((f) => f.menuID == menuID);
  if (menu_data == undefined) return;

  const menu = new ActionFormData();
  menu.title(menu_data.title);
  menu.body(menu_data.body);
  menu_data.buttons.forEach((button) => {
    menu.button(button.title, button.icon);
  });

  menu.show(player).then((result) => {
    if (result.canceled) return;

    const button = menu_data.buttons[result.selection];
    if (button.callback) {
      button.callback(player);
    } else if (button.connectID) {
      openMenu(player, button.connectID);
    }
  });
}

function locateBiome(player, biomeName) {
  const command = `/execute at @s as @s run locate biome minecraft:${biomeName}`;
  player
    .runCommandAsync(`locate biome minecraft:${biomeName}`)
    .then(() => {
      player.sendMessage(`§aScanning for ${biomeName} biome...`);
    })
    .catch(() => {
      player.sendMessage(`§cCould not locate ${biomeName} biome.`);
    });
}
