import { EquipmentSlot, EntityComponentTypes, BlockPermutation, ItemStack, system } from "@minecraft/server";
import { ActionFormData, ModalFormData } from "@minecraft/server-ui";
import { setBlock, sendPlayerCommunication } from "../main.js";
import * as db from "../database/blocks.js";
import { stateManager, particleBlocks } from "../main.js";
function guiTextureSelect(player, block, category, filteredText = "", dropdownDefault = 0) {
  let textureSelectForm = new ModalFormData().title(rawtextLang("texture_title"));
  textureSelectForm.textField(rawtextLang("filter_title"), rawtextLang("filter_placeholder"), "");
  if (filteredText != "")
    textureSelectForm.dropdown(rawtextLangWith("dropdown_filtered", [filteredText]), category, dropdownDefault);
  else
    textureSelectForm.dropdown(rawtextLang("dropdown"), category, dropdownDefault);
  if (block.typeId.includes("iron_fence")) {
    textureSelectForm.toggle("Disable Diagonal Mode", player.getDynamicProperty("diagonalMode"));
  }
  player.playSound(`maca_probuilder.tool.menu`);
  textureSelectForm.show(player).then((response) => {
    if (response.canceled)
      return;
    const [textField, dropdown, diagonalMode] = response.formValues;
    const selectedBlock = category[dropdown];
    if (textField != "") {
      const blocksFiltered = category.filter((str) => str.toLowerCase().includes(textField.toLowerCase()));
      guiTextureSelect(player, block, blocksFiltered, textField.toLowerCase());
    } else {
      setBlock(player, block, category[dropdown]);
      if (block.typeId.includes("iron_fence")) {
        player.setDynamicProperty("diagonalMode", diagonalMode);
      }
      const equippableComponent = player.getComponent(EntityComponentTypes.Equippable);
      const itemStack = equippableComponent.getEquipment(EquipmentSlot.Mainhand);
      if (itemStack == void 0 || !itemStack)
        return;
      itemStack.setLore([`${selectedBlock}`]);
      equippableComponent.setEquipment(EquipmentSlot.Mainhand, itemStack);
    }
  }).catch((e) => {
    console.error(e, e.stack);
  });
}
function guiVariantSelect(player, block, category, filteredText = "", dropdownDefault = 0) {
  let textureSelectForm = new ModalFormData().title(rawtextLang("variant_title"));
  textureSelectForm.textField(rawtextLang("filter_title"), rawtextLang("filter_placeholder"), "");
  if (filteredText != "")
    textureSelectForm.dropdown(rawtextLangWith("dropdown_filtered", [filteredText]), category, dropdownDefault);
  else
    textureSelectForm.dropdown(rawtextLang("dropdown"), category, dropdownDefault);
  player.playSound(`maca_probuilder.tool.menu`);
  textureSelectForm.show(player).then((response) => {
    if (response.canceled)
      return;
    const [textField, dropdown] = response.formValues;
    const selectedBlock = category[dropdown];
    if (textField != "") {
      const blocksFiltered = category.filter((str) => str.toLowerCase().includes(textField.toLowerCase()));
      guiVariantSelect(player, block, blocksFiltered, textField.toLowerCase());
    } else {
      const newBlockId = `maca_probuilder:${db.blocks.find((x) => x.name === selectedBlock)?.id}`;
      const blockStates = block.permutation.getAllStates();
      var newBlockStates = BlockPermutation.resolve(newBlockId);
      for (const state in blockStates) {
        if (newBlockStates.getState(state) == void 0)
          continue;
        newBlockStates = newBlockStates.withState(state, blockStates[state]);
      }
      block.setPermutation(newBlockStates);
    }
  }).catch((e) => {
    console.error(e, e.stack);
  });
}
function guiConnectDirection(player, block, states) {
  let Chimney = 0;
  if (block.hasTag("maca_probuilder:is_connected_vertical")) {
    Chimney = 2;
  }
  if (block.hasTag("maca_probuilder:is_connected_pipe")) {
    Chimney = 6;
  }
  let directionSelectForm = new ModalFormData().title("Connection Direction Manager");
  for (const state of states) {
    directionSelectForm.toggle(`${state.name}`, state.value);
  }
  ;
  const loc = block.location;
  const locationString = `${loc.x},${loc.y},${loc.z}`;
  const chimneyState = particleBlocks.has(locationString);
  if (Chimney != 0 && (chimneyState || block.above().isAir)) {
    directionSelectForm.toggle(`Chimney Mode`, chimneyState);
  }
  directionSelectForm.show(player).then((response) => {
    if (response.canceled)
      return;
    const toggleResponses = response.formValues;
    if (Chimney != 0) {
      if (toggleResponses[Chimney] == true) {
        system.run(() => {
          block.setPermutation(block.permutation.withState("maca_probuilder:connect_up", true));
        });
        if (!chimneyState) {
          stateManager(block);
        }
      } else if (chimneyState) {
        stateManager(block);
      }
    }
    let directions = [];
    if (block.hasTag("maca_probuilder:is_connected_vertical")) {
      directions = [{ dir: "up", value: 0 }, { dir: "down", value: 1 }];
    }
    if (block.hasTag("maca_probuilder:is_connected_pipe")) {
      directions = [{ dir: "up", value: 0 }, { dir: "down", value: 1 }, { dir: "north", value: 2 }, { dir: "east", value: 3 }, { dir: "south", value: 4 }, { dir: "west", value: 5 }];
    }
    if (block.hasTag("maca_probuilder:is_girder")) {
      directions = [{ dir: "north", value: 0 }, { dir: "east", value: 1 }, { dir: "south", value: 2 }, { dir: "west", value: 3 }];
    }
    for (const direction of directions) {
      block.setPermutation(block.permutation.withState(`maca_probuilder:connect_${direction.dir}`, toggleResponses[direction.value]));
    }
  }).catch((error) => {
    console.error(error, error.stack);
  });
}
function guiRotationSelect(player, block, category, filteredText = "", dropdownDefault = 0, extra = "") {
  let textureSelectForm = new ModalFormData().title(rawtextLang("rotate_title"));
  textureSelectForm.textField(rawtextLang("filter_title"), rawtextLang("filter_placeholder"), "");
  if (filteredText != "")
    textureSelectForm.dropdown(rawtextLangWith("dropdown_filtered", [filteredText]), category, dropdownDefault);
  else
    textureSelectForm.dropdown(rawtextLang("dropdown"), category, dropdownDefault);
  player.playSound(`maca_probuilder.tool.menu`);
  textureSelectForm.show(player).then((response) => {
    if (response.canceled)
      return;
    const [textField, dropdown] = response.formValues;
    const selectedBlock = category[dropdown];
    if (textField != "") {
      const blocksFiltered = category.filter((str) => str.toLowerCase().includes(textField.toLowerCase()));
      guiRotationSelect(player, block, blocksFiltered, textField.toLowerCase(), 0, extra);
    } else {
      sendPlayerCommunication(player, "rotate_success", "set_rotate", selectedBlock);
      block.setPermutation(block.permutation.withState(extra, selectedBlock.toLowerCase()));
    }
  }).catch((e) => {
    console.error(e, e.stack);
  });
}
function openToolBox(player) {
  let toolForm = new ActionFormData().title(rawtextLang("menu_title"));
  toolForm.button("Painter Tool", "textures/maca/probuilder/items/painter");
  toolForm.button("Copy Tool", "textures/maca/probuilder/items/copy");
  toolForm.button("Variant Tool", "textures/maca/probuilder/items/variant");
  toolForm.button("Rotate Tool", "textures/maca/probuilder/items/rotate");
  if (player.hasTag("maca_probuilder:editormode"))
    toolForm.button("Editor Tool", "textures/maca/probuilder/items/hammer_on");
  else
    toolForm.button("Editor Tool", "textures/maca/probuilder/items/hammer_off");
  player.playSound(`maca_probuilder.tool.menu`);
  toolForm.show(player).then((response) => {
    if (response.canceled)
      return;
    const equippableComponent = player.getComponent(EntityComponentTypes.Equippable);
    const itemStack = equippableComponent.getEquipment(EquipmentSlot.Mainhand);
    switch (response.selection) {
      case 0:
        equippableComponent.setEquipment(EquipmentSlot.Mainhand, new ItemStack("maca_probuilder:painter"));
        break;
      case 1:
        equippableComponent.setEquipment(EquipmentSlot.Mainhand, new ItemStack("maca_probuilder:copy"));
        break;
      case 2:
        equippableComponent.setEquipment(EquipmentSlot.Mainhand, new ItemStack("maca_probuilder:variant"));
        break;
      case 3:
        equippableComponent.setEquipment(EquipmentSlot.Mainhand, new ItemStack("maca_probuilder:rotate"));
        break;
      case 4:
        if (player.hasTag("maca_probuilder:editormode"))
          equippableComponent.setEquipment(EquipmentSlot.Mainhand, new ItemStack("maca_probuilder:editor_on"));
        else
          equippableComponent.setEquipment(EquipmentSlot.Mainhand, new ItemStack("maca_probuilder:editor_off"));
        break;
      default:
        break;
    }
  }).catch((e) => {
    console.error(e, e.stack);
  });
}
function rawtextLang(string) {
  return { rawtext: [{ translate: `ui.maca_probuilder.${string}` }] };
}
function rawtextLangWith(string, withText) {
  return { rawtext: [{ translate: `ui.maca_probuilder.${string}`, with: withText }] };
}
export {
  guiConnectDirection,
  guiRotationSelect,
  guiTextureSelect,
  guiVariantSelect,
  openToolBox
};
