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

system.runInterval(() => {
  // Get all crates in the world
  let crates = world
    .getDimension("overworld")
    .getEntities({ families: ["pb_plane_item_crate"] });
  crates = crates.concat(
    world
      .getDimension("nether")
      .getEntities({ families: ["pb_plane_item_crate"] })
  );
  crates = crates.concat(
    world
      .getDimension("the_end")
      .getEntities({ families: ["pb_plane_item_crate"] })
  );
  crates.forEach((crate) => {
    // Check if crate has lead attached
    const attached = crate.getComponent("leashable").isLeashed;
    // Stop if no mob or lead attached
    if (attached) return;

    // If crate has a mob and is not attached - get all drones nearby
    if (!attached) {
      // Get the first rider (mob or entity inside the crate)
      let drones = crate.dimension.getEntities({
        location: crate.location,
        maxDistance: 4,
        closest: 1,
        families: ["pb_plane_drone_passenger"],
      });

      drones.forEach((drone) => {
        const hasCargo = drone.getProperty("pb_plane:cargo_active");
        const driver = drone.getComponent("rideable").getRiders().length;
        const existingCrateId = drone.getDynamicProperty("crateId"); // Check if already has a crate

        if (hasCargo == true || driver == 0 || existingCrateId != undefined)
          return; // Prevent multiple crates

        // Attach only if no existing crate is attached
        crate.getComponent("leashable").leashTo(drone);
        drone.triggerEvent("pb_plane:cargo_active");
        crate.setDynamicProperty("leash_holder", drone.id);
        drone.setDynamicProperty("crateId", crate.id);
        drone.addEffect("slowness", 20000000, {
          amplifier: 2,
          showParticles: false,
        });
      });
    }
  });
}, 40);

//process script events
system.afterEvents.scriptEventReceive.subscribe((eventData) => {
  //id is for the id of the script command - sourceEntity is the entity that run the script command
  const { id, sourceEntity } = eventData;
  if (sourceEntity == null) return;
  // Lead check from crate a/c
  if (id == "pb_plane:leash_broken") {
    const leashHolderID = sourceEntity.getDynamicProperty("leash_holder");
    const leashHolder = getEntityByID(
      sourceEntity,
      "pb_plane:drone_passenger",
      leashHolderID
    );

    if (leashHolder == undefined) return;
    leashHolder.triggerEvent("pb_plane:cargo_inactive");
    leashHolder.addEffect("slowness", 1, {
      amplifier: 3,
      showParticles: false,
    });

    // Reset the drone's crateId property so it can pick up a new crate
    leashHolder.setDynamicProperty("crateId", undefined); // FIXED: This should be on leashHolder, not sourceEntity

    // Reset the crate's leash holder property
    sourceEntity.setDynamicProperty("leash_holder", undefined); // FIXED: This prevents reattachment issues
  }

  // Drop Cargo run from drone a/c
  if (id == "pb_plane:drop_item_cargo") {
    const crateId = sourceEntity.getDynamicProperty("crateId");
    const crate = getEntityByID(sourceEntity, "pb_plane:item_crate", crateId);

    if (crateId == undefined) return;
    crate.getComponent("leashable").unleash();
    crate.triggerEvent("pb_plane:airdrop");
    crate.addEffect("slow_falling", 200, {
      amplifier: 0,
      showParticles: false,
    });
    // Reset the drone's crateId property so it can pick up a new crate
    sourceEntity.setDynamicProperty("crateId", undefined);
    return;
  }
});
function getEntityByID(sourceEntity, type, id) {
  const entities = sourceEntity.dimension.getEntities({ type: type });
  return entities.find((entity) => entity.id == id) || null;
}
