// utils/geometryUtils.js

/**
 * Parses a point string in the format "POINT (longitude latitude)" and returns an object with latitude and longitude as numbers.
 * @param {string} position - The position string in the format "POINT (longitude latitude)".
 * @returns {{latitude: number, longitude: number}} An object containing the latitude and longitude as numbers.
 */
export const parsePoint = (position) => {
  const [longitude, latitude] = position.slice(6, -1).split(" ");
  return { latitude: parseFloat(latitude), longitude: parseFloat(longitude) };
};

/**
 * Finds the closest points on a polyline to a new point.
 * @param {Array} coordinates - The coordinates of the polyline.
 * @param {Object} newPoint - The new point (with latitude and longitude).
 * @param {Object} map - The map object.
 * @returns {Array} The closest pair of points on the polyline.
 */
export const findClosestPoints = (coordinates, newPoint, map) => {
  if (!map) {
    console.error("Map is not defined. Cannot find closest points.");
    return [];
  }

  let minDist = Infinity;
  let closestPair = [];
  for (let i = 1; i < coordinates.length; i++) {
    const dist = L.LineUtil.pointToSegmentDistance(map.latLngToLayerPoint(newPoint), map.latLngToLayerPoint(coordinates[i - 1]), map.latLngToLayerPoint(coordinates[i]));
    if (dist < minDist) {
      minDist = dist;
      closestPair = [coordinates[i - 1], coordinates[i], i];
    }
  }
  return closestPair;
};
// Hilfsfunktion zur Berechnung der Entfernung zwischen zwei Punkten (LatLng)
export function getDistance(latlng1, latlng2) {
  const R = 6371e3; // Erdradius in Metern
  const lat1 = latlng1.lat * (Math.PI / 180);
  const lat2 = latlng2.lat * (Math.PI / 180);
  const deltaLat = (latlng2.lat - latlng1.lat) * (Math.PI / 180);
  const deltaLng = (latlng2.lng - latlng1.lng) * (Math.PI / 180);

  const a = Math.sin(deltaLat / 2) * Math.sin(deltaLat / 2) + Math.cos(lat1) * Math.cos(lat2) * Math.sin(deltaLng / 2) * Math.sin(deltaLng / 2);
  const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));

  return R * c; // Entfernung in Metern
}

// Funktion zum Finden der nächsten Linie basierend auf der Mausposition
export function findNearestPolyline(map, mouseLatLng) {
  let nearestPolyline = null;
  let minDistance = Infinity;

  map.eachLayer(function (layer) {
    if (layer instanceof L.Polyline) {
      const latlngs = layer.getLatLngs();
      latlngs.forEach((latlng) => {
        const distance = getDistance(mouseLatLng, latlng);
        if (distance < minDistance) {
          minDistance = distance;
          nearestPolyline = layer;
        }
      });
    }
  });

  return nearestPolyline;
}
