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

export function orbitalCanon_MAIN(dimension) {
  system.runInterval(() => {
    dimension
      .getEntities({
        type: "tvf_randev:orbital_canon",
      })
      .forEach((ent) => {
        shooting(dimension, ent);
        check_to_despawn(dimension, ent);
      });
  }, 10);
}
function check_to_despawn(dimension, ent) {
  if (dimension.getBlock(ent.location) == undefined) return;
  if (dimension.getBlock(ent.location).typeId == "tvf_randev:orbital_canon")
    return;
  else ent.remove();
}
world.afterEvents.playerPlaceBlock.subscribe((event) => {
  const block = event.block;
  const dimension = block.dimension;
  if (block && dimension.id == "minecraft:overworld") {
    if (block.typeId == "tvf_randev:orbital_canon") {
      dimension.spawnEntity("tvf_randev:orbital_canon", {
        x: block.location.x + 0.5,
        y: block.location.y + 0.5,
        z: block.location.z + 0.5,
      });
    }
  }
});
function shooting(dimension, canon) {
  if (!canon.isValid) return;

  try {
    let meteorArr = dimension.getEntities({
      location: canon.location,
      maxDistance: 50,
      type: "tvf_randev:meteor",
      closest: 1,
    });
    meteorArr.forEach((meteor) => {
      canon.setProperty("property:has_target", true);
      let map = new MolangVariableMap();
      map.setFloat("x", meteor.location.x - canon.location.x);
      map.setFloat("y", meteor.location.y - canon.location.y - 1.6);
      map.setFloat("z", meteor.location.z - canon.location.z);
      canon.setProperty(
        "property:direction_x",
        meteor.location.x - canon.location.x
      );
      canon.setProperty(
        "property:direction_y",
        meteor.location.y - canon.location.y - 1.6
      );
      canon.setProperty(
        "property:direction_z",
        meteor.location.z - canon.location.z
      );
      dimension.spawnParticle(
        "tvf_randev:orbital_cannon",
        {
          x: canon.location.x,
          y: canon.location.y + 1.6,
          z: canon.location.z,
        },
        map
      );
      meteor.triggerEvent("tvf_randev:meteor_drop_loot");
      system.runTimeout(() => {
        if (meteor.isValid) {
          meteor.kill();
        }
      }, 40);
    });
    if (meteorArr.length == 0 && canon.getProperty("property:has_target")) {
      system.runTimeout(() => {
        if (canon.isValid) canon.setProperty("property:has_target", false);
      }, 40);
    }
  } catch {}
}
