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

world.beforeEvents.worldInitialize.subscribe(initEvent => {
  const jarOfForestWisp = [
    "nicothekid:block_jar_forest_wisp_charged",
    "nicothekid:block_jar_forest_wisp_uncharged"
  ]
  initEvent.blockTypeRegistry.registerCustomComponent("nicothekid:jar_of_forest_wisp_interaction", {
    onPlayerInteract: eventData => {
      const player = eventData.player;
      const block = eventData.block;
      const blockLocation = block.location;
      const playerEquippable = player.getComponent("equippable");
      const itemUsed = playerEquippable.getEquipment("Mainhand");
      function damageDurability () {
        system.run(() => {
          if (!player.matches({ gameMode: GameMode.creative })) {
            const itemEnchantable = itemUsed.getComponent("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)
            }
          }
        });
      }
      function decreaseItem () {
        system.run(() => {
          if (!player.matches({ gameMode: GameMode.creative })) {
            const decrementItem = itemUsed.amount == 1 ? undefined : (itemUsed.amount--, itemUsed);
            playerEquippable.setEquipment("Mainhand", decrementItem)
          }
        });
      }
      if (jarOfForestWisp.includes(block.typeId)) {
        if (itemUsed === undefined && !player.isSneaking) {
          if (block.typeId === "nicothekid:block_jar_forest_wisp_charged") {
            system.run(() => {
              block.dimension.playSound("game.player.attack.nodamage", blockLocation, { pitch: 1.1, volume: 1.0 });
              player.runCommandAsync(`tellraw @p {\"rawtext\":[{\"text\":\"§eUse the Jar Opener to release the Forest Wisp.§r\"}]}`);
            });
          }
          if (block.typeId === "nicothekid:block_jar_forest_wisp_uncharged") {
            system.run(() => {
              block.dimension.playSound("game.player.attack.nodamage", blockLocation, { pitch: 1.1, volume: 1.0 });
              player.runCommandAsync(`tellraw @p {\"rawtext\":[{\"text\":\"§eWait until it is charged. And then use the Jar Opener to release the Forest Wisp.§r\"}]}`);
            });
          }
        }
        else {
          if (block.typeId === "nicothekid:block_jar_forest_wisp_charged") {
            if (itemUsed.typeId === "minecraft:glass_bottle") {
              if (block.permutation.matches("nicothekid:block_jar_forest_wisp_charged", { "minecraft:cardinal_direction": "north" })) {
                decreaseItem ();
                block.dimension.playSound("bottle.fill", blockLocation, { pitch: 1.0, volume: 1.0 });
                player.runCommandAsync(`gamerule sendcommandfeedback false`);
                player.runCommandAsync(`give @s minecraft:experience_bottle 1`);
                player.runCommandAsync(`gamerule sendcommandfeedback true`);
                block.setPermutation(BlockPermutation.resolve("nicothekid:block_jar_forest_wisp_uncharged", { "minecraft:cardinal_direction": "north" }));
                return;
              }
              if (block.permutation.matches("nicothekid:block_jar_forest_wisp_charged", { "minecraft:cardinal_direction": "west" })) {
                decreaseItem ();
                block.dimension.playSound("bottle.fill", blockLocation, { pitch: 1.0, volume: 1.0 });
                player.runCommandAsync(`gamerule sendcommandfeedback false`);
                player.runCommandAsync(`give @s minecraft:experience_bottle 1`);
                player.runCommandAsync(`gamerule sendcommandfeedback true`);
                block.setPermutation(BlockPermutation.resolve("nicothekid:block_jar_forest_wisp_uncharged", { "minecraft:cardinal_direction": "west" }));
                return;
              }
              if (block.permutation.matches("nicothekid:block_jar_forest_wisp_charged", { "minecraft:cardinal_direction": "south" })) {
                decreaseItem ();
                block.dimension.playSound("bottle.fill", blockLocation, { pitch: 1.0, volume: 1.0 });
                player.runCommandAsync(`gamerule sendcommandfeedback false`);
                player.runCommandAsync(`give @s minecraft:experience_bottle 1`);
                player.runCommandAsync(`gamerule sendcommandfeedback true`);
                block.setPermutation(BlockPermutation.resolve("nicothekid:block_jar_forest_wisp_uncharged", { "minecraft:cardinal_direction": "south" }));
                return;
              }
              if (block.permutation.matches("nicothekid:block_jar_forest_wisp_charged", { "minecraft:cardinal_direction": "east" })) {
                decreaseItem ();
                block.dimension.playSound("bottle.fill", blockLocation, { pitch: 1.0, volume: 1.0 });
                player.runCommandAsync(`gamerule sendcommandfeedback false`);
                player.runCommandAsync(`give @s minecraft:experience_bottle 1`);
                player.runCommandAsync(`gamerule sendcommandfeedback true`);
                block.setPermutation(BlockPermutation.resolve("nicothekid:block_jar_forest_wisp_uncharged", { "minecraft:cardinal_direction": "east" }));
                return;
              }
            }
            if (itemUsed.typeId === "nicothekid:jar_opener") {
              damageDurability ();
              block.dimension.playSound("block.beehive.exit", blockLocation, { pitch: 1.0, volume: 1.0 });
              block.dimension.spawnEntity("nicothekid:forest_wisp", { x: blockLocation.x + 0.5, y: blockLocation.y + 1.0, z: blockLocation.z + 0.5 })
              block.setPermutation(BlockPermutation.resolve("nicothekid:block_jar_empty"));
              return;
            }
          }
          if (block.typeId === "nicothekid:block_jar_forest_wisp_uncharged") {
            if (itemUsed.typeId === "minecraft:glass_bottle") {
              system.run(() => {
                block.dimension.playSound("game.player.attack.nodamage", blockLocation, { pitch: 1.1, volume: 1.0 });
                player.runCommandAsync(`tellraw @p {\"rawtext\":[{\"text\":\"§eWait until it is charged.§r\"}]}`);
              });
            }
            if (itemUsed.typeId === "nicothekid:jar_opener") {
              system.run(() => {
                block.dimension.playSound("game.player.attack.nodamage", blockLocation, { pitch: 1.1, volume: 1.0 });
                player.runCommandAsync(`tellraw @p {\"rawtext\":[{\"text\":\"§eWait until it is charged.§r\"}]}`);
              });
            }
          }
        }
      }
      else return;
    }
  });
  initEvent.blockTypeRegistry.registerCustomComponent("nicothekid:jar_of_forest_wisp_tick", {
    onTick: eventData => {
      const block = eventData.block;
      const blockLocation = block.location;
      if (block.typeId === "nicothekid:block_jar_forest_wisp_uncharged") {
        if (block.permutation.matches("nicothekid:block_jar_forest_wisp_uncharged", { "minecraft:cardinal_direction": "north" })) {
          block.dimension.playSound("block.enchanting_table.use", blockLocation, { pitch: 1.3, volume: 0.8 });
          block.setPermutation(BlockPermutation.resolve("nicothekid:block_jar_forest_wisp_charged", { "minecraft:cardinal_direction": "north" }));
          return;
        }
        if (block.permutation.matches("nicothekid:block_jar_forest_wisp_uncharged", { "minecraft:cardinal_direction": "west" })) {
          block.dimension.playSound("block.enchanting_table.use", blockLocation, { pitch: 1.3, volume: 0.8 });
          block.setPermutation(BlockPermutation.resolve("nicothekid:block_jar_forest_wisp_charged", { "minecraft:cardinal_direction": "west" }));
          return;
        }
        if (block.permutation.matches("nicothekid:block_jar_forest_wisp_uncharged", { "minecraft:cardinal_direction": "south" })) {
          block.dimension.playSound("block.enchanting_table.use", blockLocation, { pitch: 1.3, volume: 0.8 });
          block.setPermutation(BlockPermutation.resolve("nicothekid:block_jar_forest_wisp_charged", { "minecraft:cardinal_direction": "south" }));
          return;
        }
        if (block.permutation.matches("nicothekid:block_jar_forest_wisp_uncharged", { "minecraft:cardinal_direction": "east" })) {
          block.dimension.playSound("block.enchanting_table.use", blockLocation, { pitch: 1.3, volume: 0.8 });
          block.setPermutation(BlockPermutation.resolve("nicothekid:block_jar_forest_wisp_charged", { "minecraft:cardinal_direction": "east" }));
          return;
        }
      }
      else return;
    }
  });
})
