import * as mc from "@minecraft/server";
import * as vector from "../utils/vector";
import * as boulder from "../entities/boulderProjectile";

export function using(event) {
  const { itemStack, source } = event;

  if (itemStack && itemStack.typeId === "hf_mzs:sculptor_staff") {
    mc.system.run(() => {
      const cooldown = itemStack.getComponent("minecraft:cooldown");
      if (cooldown.getCooldownTicksRemaining(source) < 39) return;

      if (source.getGameMode() != mc.GameMode.creative && source.getGameMode() != mc.GameMode.spectator) {
        const newItem = itemStack.clone();
        newItem.getComponent("minecraft:durability").damage += 1;
        source.getComponent("minecraft:equippable").setEquipment(mc.EquipmentSlot.Mainhand, newItem);
      }

      const pos = source.location;
      pos.x = Math.floor(pos.x) + 0.5;
      pos.y = Math.floor(pos.y) + 0.25;
      pos.z = Math.floor(pos.z) + 0.5;

      const spacing = 3;

      const dir = source.getViewDirection();
      let force = source.getViewDirection();
      dir.y = 0;

      const forwardVector = vector.normalize(dir);
      const rightVector = vector.cross(forwardVector, vector.up);
      const leftVector = vector.multiply(rightVector, -1);

      const forward = vector.add(pos, vector.multiply(forwardVector, spacing));
      const right = vector.add(pos, vector.multiply(rightVector, spacing));
      const left = vector.add(pos, vector.multiply(leftVector, spacing));

      force = vector.multiply(vector.normalize(force), 0.5);

      shootPebble(forward, force, source.dimension);
      shootPebble(right, force, source.dimension);
      shootPebble(left, force, source.dimension);
    });
  }
}

function shootPebble(location, direction, dimension) {
  let map = new mc.MolangVariableMap();
  map.setFloat("variable.lifetime", 0.4);
  map.setFloat("variable.size", 0.5);

  let parLoc = vector.subtract(location, { x: 0, y: 0.2, z: 0 });

  dimension.spawnParticle("hf_mzs:ring_grow_ground", parLoc, map);
  dimension.spawnParticle("hf_mzs:boulder_dirt", location);

  const b = dimension.spawnEntity("hf_mzs:boulder<hf_mzs:from_staff>", location);
  mc.system.runTimeout(() => {
    if (b && b.isValid()) {
      let map = new mc.MolangVariableMap();
      map.setFloat("variable.lifetime", 0.4);
      map.setFloat("variable.size", 0.5);
      let rot = (Math.atan2(direction.x, direction.z) * -180) / Math.PI;
      map.setFloat("variable.direction", rot);

      b.triggerEvent("hf_mzs:flying");
      b.setProperty("hf_mzs:launched", true);

      let parLoc = vector.add(location, { x: 0, y: 0.25, z: 0 });

      dimension.spawnParticle("hf_mzs:ring_grow", parLoc, map);

      boulder.shootBoulder(b, vector.multiply(vector.normalize(direction), 0.5));
    }
  }, 20);
}
