// /hooks/layers/useDrawLines.js
import { useEffect } from "react";
import { useDispatch, useSelector } from "react-redux";
import { fetchGisLinesThunk } from "../../redux/thunks/database/polylines/fetchGisLinesThunk";
import { selectGisLines } from "../../redux/slices/database/polylines/gisLinesSlice";

const useDrawLines = (setLinePositions) => {
  const dispatch = useDispatch();
  const gisLines = useSelector(selectGisLines);

  // Daten laden (nur einmal)
  useEffect(() => {
    dispatch(fetchGisLinesThunk());
  }, [dispatch]);

  // Linien aus GIS-Daten berechnen
  useEffect(() => {
    if (!Array.isArray(gisLines)) return;

    try {
      const newLinePositions = gisLines.map((item) => {
        if (item.points && Array.isArray(item.points)) {
          return {
            coordinates: item.points.map((point) => [point.x, point.y]),
            idModul: item.idModul,
            idLD: item.idLD,
          };
        } else {
          throw new Error("Points missing or not an array");
        }
      });

      setLinePositions(newLinePositions);
    } catch (err) {
      console.error("❌ Fehler beim Zeichnen der Linien:", err.message);
    }
  }, [gisLines, setLinePositions]);
};

export default useDrawLines;
