import type { StationDto } from "../../api/stationsApi";
import type { RequestMapItem } from "../../model/requestTypes";
import type { TguPlanUi, TguPlatformUi, TimelineRange } from "../../model/timelineTypes";
import { parseWktPolygon } from "./geometry/wktParser";
import type { Tgu2DMapLayersState } from "./model/mapLayerTypes";
import type { MapMarker, MapPolygon, Tgu2DMapScene } from "./model/mapTypes";

export type Tgu2DMapLayerAvailability = Partial<Record<keyof Tgu2DMapLayersState, string>>;

export type Tgu2DMapSceneInput = {
  range: TimelineRange;
  selectedPlan?: TguPlanUi;
  platforms: TguPlatformUi[];
  hiddenSpacecraftIds?: ReadonlySet<string>;
  requestItems?: RequestMapItem[];
  stationItems?: StationDto[];
};

const UNAVAILABLE = "Данные слоя недоступны в текущем API.";

export function buildTgu2DMapScene(input: Tgu2DMapSceneInput): Tgu2DMapScene {
  const requestPolygons = buildRequestPolygons(input.requestItems ?? []);
  const stationMarkers = buildStationMarkers(input.stationItems ?? []);

  return {
    polygons: requestPolygons,
    lines: [],
    markers: stationMarkers
  };
}

function buildRequestPolygons(items: RequestMapItem[]): MapPolygon[] {
  const polygons: MapPolygon[] = [];
  let zIndex = 0;

  for (const item of items) {
    const rings = parseWktPolygon(item.geometry);
    for (const ring of rings) {
      if (ring.length < 3) continue;
      polygons.push({
        id: `request:${item.id}:${zIndex}`,
        name: item.name,
        kind: "request",
        layer: "requests",
        points: ring,
        requestId: item.id,
        surveyType: item.surveyType,
        zIndex: zIndex++
      });
    }
  }

  return polygons;
}

export function buildStationMarkers(items: StationDto[]): MapMarker[] {
  return items.map((item, index) => ({
    id: item.id ?? `station:${index}`,
    layer: "stations" as const,
    point: { lon: item.position.long, lat: item.position.lat },
    label: item.name,
    zIndex: index,
    stationNumber: item.number,
    altitude: item.position.height,
    elevationMin: item.elevationMin,
    elevationMax: item.elevationMax
  }));
}

export function getLayerAvailability(
  layers: Tgu2DMapLayersState,
  scene: Tgu2DMapScene,
  stationsFetchFailed?: boolean
): Tgu2DMapLayerAvailability {
  const availability: Tgu2DMapLayerAvailability = {};
  if (layers.tracks && scene.lines.filter((line) => line.layer === "tracks").length === 0) {
    availability.tracks = UNAVAILABLE;
  }
  if (layers.swath && scene.polygons.filter((polygon) => polygon.layer === "swath").length === 0) {
    availability.swath = UNAVAILABLE;
  }
  if (layers.planWorks && scene.polygons.filter((polygon) => polygon.layer === "planWorks").length === 0) {
    availability.planWorks = UNAVAILABLE;
  }
  if (layers.stations && stationsFetchFailed) {
    availability.stations = UNAVAILABLE;
  }
  if (layers.spacecraftMarkers && scene.markers.filter((marker) => marker.layer === "spacecraftMarkers").length === 0) {
    availability.spacecraftMarkers = UNAVAILABLE;
  }
  return availability;
}
