import { world, system, BlockPermutation, ItemStack, GameMode } from "@minecraft/server";

world.beforeEvents.itemUseOn.subscribe(eventData => {
  const player = eventData.source;
  const itemUsed = eventData.itemStack;
  const block = eventData.block;
  const blockLocation = block.location;
  const playerEquippable = player.getComponent("equippable");
  const stateAll = block.permutation.getAllStates();
  const customAxes = [
    "nicothekid:brass_axe",
    "nicothekid:bronze_axe",
    "nicothekid:olivine_axe",
    "nicothekid:tin_axe",
    "nicothekid:zinc_axe"
  ]
  const customHoes = [
    "nicothekid:brass_hoe",
    "nicothekid:bronze_hoe",
    "nicothekid:olivine_hoe",
    "nicothekid:tin_hoe",
    "nicothekid:zinc_hoe"
  ]
  const customShovels = [
    "nicothekid:brass_shovel",
    "nicothekid:bronze_shovel",
    "nicothekid:olivine_shovel",
    "nicothekid:tin_shovel",
    "nicothekid:zinc_shovel"
  ]
  function damageDurability () {
    if (!player.matches({ gameMode: GameMode.creative })) {
      const itemEnchantable = itemUsed.getComponent("minecraft:enchantable");
      const unbreakingLevel = itemEnchantable?.getEnchantment("unbreaking")?.level ?? 0;
      const breakChance = 100 / (unbreakingLevel + 1);
      const randomizeChance = Math.random() * 100;
      if (breakChance < randomizeChance) return;
      const itemDurability = itemUsed.getComponent("durability");
      if (!itemDurability) return;
      const itemMaxDurability = itemDurability.maxDurability;
      const itemDurabilityDamage = itemDurability.damage;
      const durabilityCalculation = itemMaxDurability - itemDurabilityDamage;
      let damageAmount = 1;
      const currentDurability = durabilityCalculation - damageAmount;
      if (currentDurability <= 0) {
        player.playSound("random.break", { pitch: 0.9, location: player.location, volume: 1 });
        playerEquippable.setEquipment("Mainhand", null);
      }
      else {
        itemDurability.damage += damageAmount;
        playerEquippable.setEquipment("Mainhand", itemUsed)
      }
    }
  }
  if (itemUsed === undefined) return;
  if (itemUsed.hasTag("minecraft:is_axe") || customAxes.includes(itemUsed.typeId) || itemUsed.hasTag("minecraft:is_hoe") || customHoes.includes(itemUsed.typeId) || itemUsed.hasTag("minecraft:is_shovel") || customShovels.includes(itemUsed.typeId)) {
    if (itemUsed.hasTag("minecraft:is_axe") || customAxes.includes(itemUsed.typeId)) {
      const customWoods = [
        "nicothekid:mosshroom_stem",
        "nicothekid:mosshroom_hyphae"
      ]
      if (customWoods.includes(block.typeId)) {
        system.run(() => {
          damageDurability ();
          if (block.permutation.matches("nicothekid:mosshroom_hyphae")) {
            block.dimension.playSound("use.stem", blockLocation, { pitch: 0.8, volume: 1.0 });
            block.setPermutation(BlockPermutation.resolve("nicothekid:mosshroom_hyphae_stripped", stateAll ));
            return;
          }
          if (block.permutation.matches("nicothekid:mosshroom_stem")) {
            block.dimension.playSound("use.stem", blockLocation, { pitch: 0.8, volume: 1.0 });
            block.setPermutation(BlockPermutation.resolve("nicothekid:mosshroom_stem_stripped", stateAll ));
            return;
          }
        });
      }
    }
    if (itemUsed.hasTag("minecraft:is_hoe") || customHoes.includes(itemUsed.typeId)) {
      const myceliumedBlocks = [
        "nicothekid:myceliumed_deepslate"
      ]
      if (myceliumedBlocks.includes(block.typeId)) {
        system.run(() => {
          const pitchRange = Math.random() * (1.0 - 0.8) + 0.8;
          function spawnMyceliumSprouts () {
            const myceliumSprouts = new ItemStack ("nicothekid:mycelium_sprouts_small", 1);
            let randomChance = Math.random();
            if (itemUsed.getComponent("enchantable").hasEnchantment("silk_touch")) {
              block.dimension.spawnItem(myceliumSprouts, { x: blockLocation.x + 0.5, y: blockLocation.y + 1.0, z: blockLocation.z + 0.5 });
            }
            else if (itemUsed.getComponent("enchantable").hasEnchantment("fortune")) {
              if (itemUsed.getComponent("enchantable").getEnchantment("fortune").level == 1) {
                if (randomChance <= 0.5) {
                  block.dimension.spawnItem(myceliumSprouts, { x: blockLocation.x + 0.5, y: blockLocation.y + 1.0, z: blockLocation.z + 0.5 });
                }
              }
              if (itemUsed.getComponent("enchantable").getEnchantment("fortune").level == 2) {
                if (randomChance <= 0.75) {
                  block.dimension.spawnItem(myceliumSprouts, { x: blockLocation.x + 0.5, y: blockLocation.y + 1.0, z: blockLocation.z + 0.5 });
                }
              }
              if (itemUsed.getComponent("enchantable").getEnchantment("fortune").level == 3) {
                if (randomChance <= 1.0) {
                  block.dimension.spawnItem(myceliumSprouts, { x: blockLocation.x + 0.5, y: blockLocation.y + 1.0, z: blockLocation.z + 0.5 });
                }
              }
            }
            else {
              if (randomChance <= 0.25) {
                block.dimension.spawnItem(myceliumSprouts, { x: blockLocation.x + 0.5, y: blockLocation.y + 1.0, z: blockLocation.z + 0.5 });
              }
              else return;
            }
          }
          damageDurability ();
          spawnMyceliumSprouts ();
          block.dimension.playSound("use.gravel", blockLocation, { pitch: pitchRange, volume: 0.8 });
          if (block.permutation.matches("nicothekid:myceliumed_deepslate")) {
            block.setPermutation(BlockPermutation.resolve("minecraft:deepslate"));
          }
        });
      }
    }
  }
  else return;
});
