/*console.warn("weapons.js loaded");
*/

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

const weaponsList = new Set([
  "aria_ah:greatsword",
  "aria_ah:tentaclesword",
  "aria_ah:scythe",
]);

world.afterEvents.itemUse.subscribe(({ source: entity, itemStack: item }) => {
  if (!(entity instanceof Player)) return;

  // First check if it's a weapon from the list
  if (item && weaponsList.has(item.typeId)) {
    // Then check for morph tag
    if (entity.hasTag("aria_ah_is_morphed")) {
      entity.sendMessage({
        rawtext: [{ translate: "aria_ah.cant_use_weapon_in_morph" }]
      });
      return;
    }

    const cooldown = item.getComponent("minecraft:cooldown");
    if (!cooldown) return;

    const remainingTicks = cooldown.getCooldownTicksRemaining(entity);
    if (
      remainingTicks > 0 &&
      (world.scoreboard.getObjective("aria_ah.weapons").getScore(entity) ?? 0) === 0
    ) {
      const remainingSeconds = (remainingTicks / 20).toFixed(1);
      entity.onScreenDisplay.setActionBar({
        rawtext: [{
          translate: "aria_ah.cooldown.seconds",
          with: [remainingSeconds]
        }]
      });
      return;
    }

    cooldown.startCooldown(entity);

    const weaponsFunctions = {
      "aria_ah:greatsword": "function aria/ah/weapons/GreatSword",
      "aria_ah:tentaclesword": "function aria/ah/weapons/TentacleSword",
      "aria_ah:scythe": "function aria/ah/weapons/Scythe",
    };

    entity.addTag(`aria_ah_wp_${item.typeId.split(":")[1]}`);
    entity.runCommand(weaponsFunctions[item.typeId]);
    damageItem(entity, 5, item);
  }
});



system.afterEvents.scriptEventReceive.subscribe(
  ({ sourceEntity: entity, id, message: msg }) => {
    if (id === "aria_ah:apply_knockback") {
      const direction = entity.getViewDirection();
      const multiplier = getArmorMultiplier(entity);
      const [horizontal, vertical] = msg.split(",").map(Number);
      try {
        entity.applyKnockback(
          {
            x: direction.x * horizontal * multiplier,
            z: direction.z * horizontal * multiplier
          },
          vertical * multiplier
        );
      } catch {}
    }
  }
);

function getArmorMultiplier(player) {
  if (!(player instanceof Player)) return 1;

  const slots = ["Head", "Chest", "Legs", "Feet"];
  let multiplier = 1;

  for (const slot of slots) {
    const equipment = player.getComponent("equippable")?.getEquipmentSlot(slot);
    if (equipment?.hasItem() && equipment.typeId.includes("netherite")) {
      multiplier += 0.168;
    }
  }

  return multiplier;
}

/*
world.beforeEvents.playerBreakBlock.subscribe((e) => {
  system.run(() => {
    damageItem(e.player, 1, e.itemStack);
  });
});
*/

world.afterEvents.entityHitEntity.subscribe((e) => {
  let { damagingEntity, hitEntity } = e;
  if (damagingEntity.typeId != "minecraft:player") return;
  const weapons = [
    "aria_ah:greatsword",
    "aria_ah:scythe",
    "aria_ah:tentaclesword",
  ];
  let item = damagingEntity
    .getComponent("equippable")
    .getEquipment(EquipmentSlot.Mainhand);
  if (!weapons.includes(item?.typeId)) return;
  if (item == undefined) return;
  let offset = 6;
  damagingEntity.dimension.spawnParticle("aria_ah:slash_new_slash", {
    x: hitEntity.location.x + 0.5,
    y: damagingEntity.getHeadLocation().y,
    z: hitEntity.location.z + 0.5,
  });
  damagingEntity.dimension.playSound(
    "aria_ah.sfx.sword_swing",
    damagingEntity.location
  );
  system.run(() => {
    try {
      damageItem(damagingEntity, 1, item);
    } catch {}
  });
});

function damageItem(e, d, i) {
  var dur = i.getComponent("minecraft:durability");
  var u = 0;
  if (i.hasComponent("enchantments")) {
    u = i
      .getComponent("enchantments")
      .enchantments.getEnchantment("unbreaking");
    if (!u) {
      u = 0;
    } else {
      u = u.level;
    }
  }
  if (u > 0) {
    if (Math.random() * u < u / (u + 1) ? true : false) {
      dur.damage += Math.round(d / u);
    }
  } else {
    try {
      dur.damage += d;
    } catch {
      dur.damage = dur.maxDurability;
    }
  }
  if (e.getGameMode() == "creative") return;
  if (dur.damage == dur.maxDurability) {
    breakItem(e);
  } else {
    e.getComponent("minecraft:equippable").setEquipment(
      EquipmentSlot.Mainhand,
      i
    );
  }
}
