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

// CAMERA FUNCTION - checks the vehicle type and apply settings to camera
function setPlayerCamera(player, getRide) {
  // Check if the ride and player exist
  if (!getRide || !player) return;

  // Retrieve the shift values based on the vehicle typeId
  const vehicle = Object.values(vehiclesValues).find(
    (v) => v.typeId === getRide.typeId
  );

  if (vehicle) {
    // Calculate the camera shift based on the vehicle's shift values
    const z_direction_shift = vectorMultiply(
      player.getViewDirection(),
      vehicle.z_camera_shift
    );

    const camera_location = vectorAdd(z_direction_shift, {
      x: player.location.x,
      y: player.location.y + vehicle.y_camera_shift,
      z: player.location.z,
    });

    //if (vehicle.type == "plane") {
      // Set the camera to the calculated location
      player.camera.setCamera("minecraft:free", {
        location: camera_location,
        facingEntity: { facingEntity: player },
        rotation: player.getRotation(),
        easeOptions: { easeTime: 0.8, easeType: "Linear" }
      });
    //}
  }
}

// MULTIPLY MATH
function vectorMultiply(vector, multiplier) {
  return {
    x: vector.x * multiplier,
    y: vector.y * multiplier,
    z: vector.z * multiplier,
  };
}

// ADD MATH
function vectorAdd(vector1, vector2) {
  return {
    x: vector1.x + vector2.x,
    y: vector1.y + vector2.y,
    z: vector1.z + vector2.z,
  };
}

// Add the interval function to set the camera for players in vehicles
system.runInterval(() => {
  for (const player of world.getPlayers()) {
    // Check if the player has the camera tag
    if (player.hasTag("pb_dino_vehicle_camera")) {
      const getRide = player.getComponent("minecraft:riding")?.entityRidingOn;
      setPlayerCamera(player, getRide);
    }
  }
});
