import {
  world,
  Items,
  ItemStack,
  Location,
  Entity,
  ItemEnchantsComponent,
  ItemTypes,
  EntityInventoryComponent,
  Block,
  Enchantment,
  MinecraftEnchantmentTypes,
} from "@minecraft/server";
import {
  ActionFormData,
  MessageFormData,
  ModalFormData,
} from "@minecraft/server-ui";
import { getPlayerExperienceLevel } from 'get_level_tests'
world.events.beforeItemUseOn.subscribe((use) => {
  let player = use.source,
    item = use.item;
  let blockTest = world
    .getDimension(player.dimension.id)
    .getBlock(use.blockLocation);
  if (
    (item?.typeId == "pog:stone_axe") |
      (item?.typeId == "pog:iron_axe") |
      (item?.typeId == "pog:diamond_axe") |
      (item?.typeId == "pog:netherite_axe") &&
    blockTest?.typeId == "pog:enchant_bench"
  ) {
    veinMine(player);
  }
});

function veinMine(player) {
  let level = player.runCommandAsync("xp 0 @s").level;
  let form = new ActionFormData();
  form.title("Enchant axe?");
  form.body(
    "You are about to enchant your axe with Tree Capitator I.\n\nYou need 1 Tree Capitator Book and 6 xp levels to enchant your axe"
  );
  ///buttons
  form.button("Enchant");
  form.button("Don't Enchant");
  form.show(player).then((response) => {
    if (response.selection == 0 && getPlayerExperienceLevel(player) >= 6) {
      console.warn("Dust");
      const inventory = player.getComponent(
        EntityInventoryComponent.componentId
      );
      for (let slot = 0; slot < inventory.container.size; slot++) {
        const itemStack = inventory.container.getItem(slot);
        if (itemStack?.typeId === "pog:tree_cap_book") {
          let inv = player.getComponent("inventory").container;
          let item = inv.getItem(player.selectedSlot);
          let newItem = new ItemStack(ItemTypes?.get("pog:stone_axe"));
          if (item?.typeId == "pog:stone_axe") {
            item?.setLore(["§r§7Tree Capitator I"]);
            player.runCommandAsync("clear @p pog:tree_cap_book 0 1");
            player.runCommandAsync("xp -6l @p");
            inv.setItem(player.selectedSlot, item);
            player.runCommandAsync("enchant @p efficiency 1");
          }
          if (item?.typeId == "pog:iron_axe") {
            item?.setLore(["§r§7Tree Capitator I"]);
            player.runCommandAsync("clear @p pog:tree_cap_book 0 1");
            player.runCommandAsync("xp -6l @p");
            inv.setItem(player.selectedSlot, item);

            player.runCommandAsync("enchant @p efficiency 1");
          }
          if (item?.typeId == "pog:diamond_axe") {
            item?.setLore(["§r§7Tree Capitator I"]);
            player.runCommandAsync("clear @p pog:tree_cap_book 0 1");
            player.runCommandAsync("xp -6l @p");
            inv.setItem(player.selectedSlot, item);

            player.runCommandAsync("enchant @p efficiency 1");
          }
          if (item?.typeId == "pog:netherite_axe") {
            item?.setLore(["§r§7Tree Capitator I"]);
            player.runCommandAsync("clear @p pog:tree_cap_book 0 1");
            player.runCommandAsync("xp -6l @p");
            inv.setItem(player.selectedSlot, item);

            player.runCommandAsync("enchant @p efficiency 1");
          }
        }
      }
    } else if (response.selection == 0 && getPlayerExperienceLevel(player) < 6) {
      player.tell("§cYou don't have enough levels.")
    }
    if (response.selection == 1) {
      console.warn("Spare");
    }
  });
}
var blockCount = 0;

async function a(block, done, starting) {
  for (let player of world.getPlayers()) {
  const id = `${block.x} ${block.y} ${block.z}`;
  if (done.has(id)) {
    return;
  }
  done.add(id);
  if (
    starting ||
    block.hasTag("log") ||
    block.typeId == "minecraft:mangrove_log"
  ) {
    let players = world.getPlayers();
    await null;
      let inv = player.getComponent("inventory").container;
      let item = inv.getItem(player.selectedSlot);
      let lore = item.getLore();
      if (lore.includes("§r§7Tree Capitator I")) {
        blockCount += 1;
        item.getComponent("durability").damage =
          item.getComponent("durability").damage + 1;

        item.setLore(["§r§7Tree Capitator I"]);
        inv.setItem(player.selectedSlot, item);
      }
      (async (res) => {
        res(
          block.dimension.runCommandAsync(
            `setblock ${block.x} ${block.y} ${block.z} air 0 destroy`
          )
        );
      })();
      for (let x = -1; x <= 1; x++) {
        for (let y = -1; y <= 1; y++) {
          for (let z = -1; z <= 1; z++) {
            if (x === 0 && y === 0 && z === 0) {
              continue;
            }
            a(block.dimension.getBlock(block.location.offset(x, y, z)), done);
          }
        }
      }
  }
}}

async function e(block, done, starting, player) {
  const id = `${block.x} ${block.y} ${block.z}`;
  let players = world.getPlayers();
    let inv = player.getComponent("inventory").container;
    let item = inv.getItem(player.selectedSlot);
    let lore = item.getLore();
    if (done.has(id)) {
      return;
    }
    done.add(id);
    if (
      starting ||
      block.hasTag("log") ||
      block.typeId == "minecraft:mangrove_log"
    ) {
      blockCount += 1;
      if (lore.includes("§r§7Tree Capitator I")) {
        (async (res) => {
          item.getComponent("durability").damage =
            item.getComponent("durability").damage + blockCount;
          item.setLore(["§r§7Tree Capitator I"]);
          inv.setItem(player.selectedSlot, item);
          console.warn(blockCount);
          console.warn(item.getComponent("durability").damage);

          block.dimension.runCommandAsync(
            `setblock ${block.x} ${block.y} ${block.z} air 0 destroy`
          );
        })().catch((e) => console.error(e, e.stack));
        for (let x = -1; x <= 1; x++) {
          for (let y = -1; y <= 1; y++) {
            for (let z = -1; z <= 1; z++) {
              if (x === 0 && y === 0 && z === 0) {
              }

              e(block.dimension.getBlock(block.location.offset(x, y, z)), done);
            }
          }
        }
      }
    }
}

world.events.blockBreak.subscribe(
  ({ block, player, brokenBlockPermutation }) => {
    let inv = player.getComponent("inventory").container;
    let item = inv.getItem(player.selectedSlot);
    let lore = item?.getLore();
    if (
      brokenBlockPermutation.type.id == "minecraft:log" ||
      brokenBlockPermutation.type.id == "minecraft:mangrove_log" ||
      brokenBlockPermutation.type.id == "minecraft:log2"
    ) {
      if (
        item?.typeId == "pog:wooden_axe" ||
        item?.typeId == "pog:stone_axe" ||
        item?.typeId == "pog:iron_axe" ||
        item?.typeId == "minecraft:gold_axe" ||
        item?.typeId == "pog:diamond_axe" ||
        item?.typeId == "pog:netherite_axe"
      ) {
        if (lore.includes("§r§7Tree Capitator I")) {
          if (
            item.getComponent("durability").damage <
            item.getComponent("durability").maxDurability
          ) {
            blockCount = 0;
            a(block, new Set(), true);
          }
        }
      }
    }
  }
);
