import { system } from "@minecraft/server";
import {
  releaseCarriedEntity,
  TRACTOR_DURATION_TICKS,
} from "./vehicleUFOTractorUtils.js";

// Handles when a player interacts with the UFO (toggles tractor beam)
system.afterEvents.scriptEventReceive.subscribe((eventData) => {
  const { id, sourceEntity } = eventData;
  if (id !== "pb_plane:tractor_trigger") return;
  if (!sourceEntity || !sourceEntity.dimension) return;

  const ufo = sourceEntity;
  const isActive = ufo.getProperty("pb_plane:tractor_active") === true;
  const isCarrying = ufo.getProperty("pb_plane:tractor_carrying") === true;

  // If already carrying something, treat this as a "release" toggle
  if (isCarrying) {
    releaseCarriedEntity(ufo);
    ufo.setProperty("pb_plane:tractor_active", false);
    ufo.setProperty("pb_plane:tractor_carrying", false);
    return;
  }

  // If tractor is already active but hasn't picked up yet, do nothing
  if (isActive) return;

  // Activate tractor beam (begins scan cycle)
  ufo.setProperty("pb_plane:tractor_active", true);

  // After timeout, deactivate beam if nothing has been picked up
  system.runTimeout(() => {
    const stillActive = ufo.getProperty("pb_plane:tractor_active") === true;
    const stillCarrying = ufo.getProperty("pb_plane:tractor_carrying") === true;

    if (stillActive && !stillCarrying) {
      ufo.setProperty("pb_plane:tractor_active", false);
    }
  }, TRACTOR_DURATION_TICKS);
});
