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

// Subscribe to the `itemReleaseUse` event, which is triggered when a player releases the use of an item
world.afterEvents.itemReleaseUse.subscribe((eventData) => {
  const { source, itemStack, useDuration } = eventData;
  const equipment = source.getComponent('equippable');
  const selectedItem = equipment.getEquipment('Mainhand');
  if (itemStack.getTags().includes('minecraft:is_spear')) {
    const s = world.scoreboard.getObjective('Spear_use_time');
    s.setScore(source, 1)
  }
  if (selectedItem.hasTag("edx:summoning_book") && useDuration < 170 && (getScore(source, 'summoning_cooldown_score') === 0)) {
    const playerID = source.id
    if (getScore(source, 'Summoned_entity_number') > 0) {
      source.runCommand(`event entity @e[tag="${playerID}"] minecraft:despawn`)
      source.runCommand(`scoreboard players set @s Summoned_entity_number 0`)
      source.dimension.playSound('soul_book.use', source.location);
      world.getDimension(source.dimension.id).spawnParticle('edx:soul_summoning_book_use', source.getHeadLocation());
    }
    if (selectedItem.typeId == "edx:soul_summoning_book") { //Soul summoning book
      source.runCommand(`scoreboard players add @s Summoned_entity_number 1`)
      const entity_summon = source.dimension.spawnEntity("edx:vengeful_soul", { x: source.location.x + source.getViewDirection().x, y: source.location.y, z: source.location.z + source.getViewDirection().z })
      const tameable = entity_summon.getComponent("minecraft:tameable"); // le mob summon doit avoir le component minecraft:tameable
      tameable.tame(source);
      entity_summon.addTag(playerID);
      source.runCommand(`scoreboard players set @s summoning_cooldown_score 88`)
    }
  }
  if (selectedItem.typeId == "edx:blaze_blade" && useDuration < 170) {
    const view = source.getViewDirection()
    const head = source.getHeadLocation()
    const direction = { x: head.x + view.x, y: head.y + view.y, z: head.z + view.z }
    source.dimension.spawnEntity('edx:fire_strike', direction).getComponent("minecraft:projectile").shoot(view);
    source.dimension.playSound('mob.blaze.shoot', source.location);
    Damage(source, itemStack)
  }
});