import { world, system } from "@minecraft/server";
import vehiclesValues from "./VehicleValues.js";
import { vehicleCheck } from "./VehicleMovementUtil.js";

function setHoverState(driver, vehicle) {
  // sets the hoverstate if the player double taps the ascend button in a 75-300ms timeframe.
  let timeElapsed =
    driver.getDynamicProperty("end") - driver.getDynamicProperty("start");
  if (timeElapsed > 75 && timeElapsed < 300) {
    vehicle?.addTag("pb_dino_hovering");
    return true;
  } else {
    vehicle?.removeEffect("slow_falling");
    vehicle?.addEffect("levitation", 20, {
      amplifier: 5,
      showParticles: false,
    });
    driver.onScreenDisplay.setActionBar(
      "Hover Mode: §4§lOff§r - double tap jump to activate"
    );
    vehicle?.removeTag("pb_dino_hovering");
    return false;
  }
}

// Main loop to check and display speed
system.runInterval(() => {
  for (const player of world.getPlayers()) {
    if (vehicleCheck(player)) {
      // Get vehicle information
      const vehicle = player.getComponent("minecraft:riding").entityRidingOn; // Vehicle player is riding
      const driver = vehicle?.getComponent("minecraft:rideable").getRiders()[0];

      // Only apply movement logic to the driver
      if (driver !== player) continue; // Skip this player if they are not the driver

      const vehicleTypeId = vehicle.typeId; // Type id of vehicle
      const vehicleData = Object.values(vehiclesValues).find(
        // Vehicle values from import
        (v) => v.typeId === vehicleTypeId
      );

      // Fuel check
      const hasFuel = vehicle?.getProperty("pb_dino:has_fuel");
      // Environment check

      if (vehicleData.type == "heli") {
        if (driver.isJumping) {
          if (!hasFuel) {
            driver.onScreenDisplay.setActionBar(
              "Insert fuel into the helicopters equipment slot to fly"
            );
            return;
          }
          driver.setDynamicProperty("end", Date.now());
          // Check "HoverState" - if jump is pressed again, add tag, return TRUE, if not, remove tag, return FALSE
          if (!setHoverState(driver, vehicle))
            driver.setDynamicProperty("start", Date.now());
        }
        // If not holding jump, but helicopter has tag "hovering" - IN HOVER MODE
        else if (vehicle?.hasTag("pb_dino_hovering")) {
          vehicle?.applyImpulse({ x: 0, y: 0, z: 0 });
          driver.onScreenDisplay.setActionBar(
            "Hover Mode: §2§lOn§r - press jump to de-activate"
          );
        }
        // Not jumping and not on ground
        else if (!vehicle?.isOnGround) {
          vehicle?.removeTag("pb_dino_hovering");
          vehicle?.removeEffect("levitation");
          vehicle?.addEffect("slow_falling", 20, {
            amplifier: 0,
            showParticles: false,
          });
        }
      }
    }
  }
});
