import { world, GameMode } from "@minecraft/server";
import { Damage } from "./item_components.js";
import { getScore } from "../utils/score.js";

function isFamily(family, entity) {
  return entity?.getComponent("minecraft:type_family")?.hasTypeFamily(family);
}

export function Attack(player) {
  let itemUsed = player.getComponent("equippable").getEquipment("Mainhand");
  if (itemUsed != null) {
    if (itemUsed?.getTags()?.includes("minecraft:is_sword")) {
      player.runCommand(`scoreboard players set @s Hit_cooldown 10`);
    }
    else if (itemUsed?.getTags()?.includes("minecraft:is_spear")) {
      const mount = player?.getComponent('riding')?.entityRidingOn
      const lungeLevel = itemUsed?.getComponent("minecraft:enchantable")?.getEnchantment("lunge")?.level
      if (player.hasTag("hussars_spear") && mount != undefined && lungeLevel>0) {
        const power = lungeLevel*2.6
        mount.applyKnockback({x: player.getViewDirection().x * power,z: player.getViewDirection().z * power,},0.1)
      }
    }
  }
}

export function SpearsNormalAttack(victim, player) {
  if(player.typeId!="minecraft:player") return;
  let itemUsed = player.getComponent("equippable").getEquipment("Mainhand");
  let offhandItem = player.getComponent("equippable").getEquipment("Offhand");
  if (itemUsed?.getTags()?.includes("minecraft:is_spear")) {
    if (player.hasTag("shield_spear") && itemUsed?.getComponent("minecraft:enchantable")?.getEnchantment("lunge")?.level > 0 && offhandItem.typeId == "minecraft:shield") {
      victim.addEffect("slowness", 30, { amplifier: 4 });
    }
  }
}

export function SpearsAnyAttack(victim,player)
{
  if(player?.typeId!="minecraft:player" || victim?.typeId=="minecraft:player") return;
  let itemUsed = player.getComponent("equippable").getEquipment("Mainhand");
  
  if (itemUsed?.getTags()?.includes("minecraft:is_spear") && player.hasTag("sharper_spear") && world.scoreboard.getObjective('Spear_use_time').getScore(player)>0) {
    const velocity = Math.sqrt((player.getVelocity().x)**2+(player.getVelocity().z)**2)
    if(velocity<0.5)return
    const rand = Math.random()
    if(rand<1/4)
    {
      victim.runCommand(`replaceitem entity @s slot.armor.head 0 air`);
    }
    else if(rand<1/2)
    {
      victim.runCommand(`replaceitem entity @s slot.armor.chest 0 air`);
    }
    else if(rand<3/4)
    {
      victim.runCommand(`replaceitem entity @s slot.armor.legs 0 air`);
    }
    else
    {
      victim.runCommand(`replaceitem entity @s slot.armor.feet 0 air`);
    }
  }
}