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

world.afterEvents.itemUse.subscribe(eventData => {
  const player = eventData.source;
  const itemUsed = eventData.itemStack;
  const playerEquippable = player.getComponent("equippable");
  const customStaff = [
    "nicothekid:blazing_staff",
    "nicothekid:curserer_staff",
    "nicothekid:piglin_fire_staff",
    "nicothekid:powder_staff",
    "nicothekid:staff_of_the_sea"
  ]
  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 (customStaff.includes(itemUsed.typeId)) {    
    if (itemUsed.typeId === "nicothekid:blazing_staff") {
      const cooldown = itemUsed.getComponent("cooldown").getCooldownTicksRemaining(player);
      if (cooldown == 47) {
        let projectileEntity = player.dimension.spawnEntity("nicothekid:projectile_blazing_missile", {
          x: player.location.x + (player.getViewDirection().x),
          y: player.location.y + 1.5 + (player.getViewDirection().y),
          z: player.location.z + (player.getViewDirection().z)
        });
        let projectileComponent = projectileEntity.getComponent("minecraft:projectile");
        let velocity = { x: player.getViewDirection().x, y: player.getViewDirection().y, z: player.getViewDirection().z };
        projectileComponent.owner = player;
        projectileComponent.shoot( velocity );
        player.playSound("mob.ghast.fireball", { pitch: 2.0, location: player.location, volume: 1.0 });
        player.playAnimation("attack");
        damageDurability ();
      }
    }
    if (itemUsed.typeId === "nicothekid:curserer_staff") {
      const cooldown = itemUsed.getComponent("cooldown").getCooldownTicksRemaining(player);
      if (cooldown == 43) {
        let projectileEntity = player.dimension.spawnEntity("nicothekid:projectile_curserer_missile",{
          x: player.location.x + (player.getViewDirection().x),
          y: player.location.y + 1.5 + (player.getViewDirection().y),
          z: player.location.z + (player.getViewDirection().z)
        });
        let projectileComponent = projectileEntity.getComponent("minecraft:projectile");
        let velocity = { x: player.getViewDirection().x, y: player.getViewDirection().y, z: player.getViewDirection().z };
        projectileComponent.owner = player;
        projectileComponent.shoot( velocity );
        player.playSound("mob.shulker.shoot", { pitch: 1.5, location: player.location, volume: 1.0 });
        player.playAnimation("attack");
        damageDurability ();
      }
    }
    if (itemUsed.typeId === "nicothekid:piglin_fire_staff") {
      const cooldown = itemUsed.getComponent("cooldown").getCooldownTicksRemaining(player);
      if (cooldown == 43) {
        let projectileEntity = player.dimension.spawnEntity("nicothekid:projectile_fire_spike", {
          x: player.location.x + (player.getViewDirection().x),
          y: player.location.y + 1.5 + (player.getViewDirection().y),
          z: player.location.z + (player.getViewDirection().z)
        });
        let projectileComponent = projectileEntity.getComponent("minecraft:projectile");
        let velocity = { x: player.getViewDirection().x, y: player.getViewDirection().y, z: player.getViewDirection().z };
        projectileComponent.owner = player;
        projectileComponent.shoot( velocity );
        player.playSound("mob.ghast.fireball", { pitch: 1.5, location: player.location, volume: 1.0 });
        player.playAnimation("attack");
        damageDurability ();
      }
    }
    if (itemUsed.typeId === "nicothekid:powder_staff") {
      const cooldown = itemUsed.getComponent("cooldown").getCooldownTicksRemaining(player);
      const offhandItem = playerEquippable.getEquipment("Offhand");
      const customPowder = [
        "nicothekid:amethyst_powder",
        "nicothekid:charcoal_powder",
        "nicothekid:cocoa_powder",
        "nicothekid:diamond_powder",
        "nicothekid:emerald_powder",
        "nicothekid:enchanted_dust",
        "nicothekid:gold_powder",
        "nicothekid:iron_powder",
        "nicothekid:lapis_lazuli_powder",
        "nicothekid:netherite_powder"
      ]
      if (offhandItem === undefined || !customPowder.includes(offhandItem.typeId)) {
        if (cooldown == 43) {
          player.playSound("game.player.attack.nodamage", { pitch: 1.1, location: player.location, volume: 1.0 });
          player.runCommandAsync(`tellraw @p {\"rawtext\":[{\"text\":\"§eYou don't have any powder materials in your off-hand to use as a projectile.§r\"}]}`);
          system.runTimeout(() => {
            player.startItemCooldown("powder_staff", 0 );
            return;
          }, 5);
        }
        else return;
      }
      else if (customPowder.includes(offhandItem.typeId)) {
        if (cooldown == 43) {
          player.playSound("mob.shulker.shoot", { pitch: 1.5, location: player.location, volume: 1.0 });
          player.playAnimation("attack");
        }
        else return;
      }
      else return;
    }
    if (itemUsed.typeId === "nicothekid:staff_of_the_sea") {
      const cooldown = itemUsed.getComponent("cooldown").getCooldownTicksRemaining(player);
      const playerOnBlock = player.dimension.getBlock({ x: player.location.x, y: player.location.y + 0.5, z: player.location.z });
      const validWater = [
        "minecraft:flowing_water",
        "minecraft:water"
      ]
      if (!validWater.includes(playerOnBlock.typeId)) {
        if (cooldown == 799) {
          player.playSound("game.player.attack.nodamage", { pitch: 1.1, location: player.location, volume: 1.0 });
          player.runCommandAsync(`tellraw @p {\"rawtext\":[{\"text\":\"§eYou have to be in water to activate the staff's effect§r\"}]}`);
          system.runTimeout(() => {
            player.startItemCooldown("staff_of_the_sea", 0 );
            return;
          }, 10);
        }
        else return;
      }
      else if (validWater.includes(playerOnBlock.typeId) && cooldown == 799) {
        if (cooldown == 799) {
          player.addEffect("conduit_power", 1800, {amplifier: 0, showParticles: false })
          player.playSound("conduit.activate", { pitch: 1.1, location: player.location, volume: 1.0 });
          player.playAnimation("attack");
          player.dimension.spawnParticle("nicothekid:staff_of_the_sea_activation_particle", { x: player.location.x, y: player.location.y + 0.5, z: player.location.z });
          damageDurability ();
        }
        else return;
      }
      else return;
    }
  }
  else return;
});
