import {
  createCircleFeature,
  createLineFeature,
  createPolygonFeature,
  type DrawingFeatureCollection
} from "./drawing-layers";
import { getDistanceMeters, type LngLatTuple } from "./geo";

export type WorkbenchDrawMode = "point" | "line" | "polygon" | "circle";

export type DrawingDraftState =
  | {
      mode: "line" | "polygon";
      coordinates: LngLatTuple[];
    }
  | {
      mode: "circle";
      center: LngLatTuple;
      edge?: LngLatTuple;
    };

export function createDrawingId(mode: WorkbenchDrawMode, index: number) {
  return `${mode}-${index.toString().padStart(3, "0")}`;
}

export function createDrawingLabel(mode: WorkbenchDrawMode, index: number) {
  return `${getDrawingKindLabel(mode)} ${index.toString().padStart(2, "0")}`;
}

export function createFeatureFromDraft(
  id: string,
  draft: DrawingDraftState,
  label: string
): DrawingFeatureCollection["features"][number] | null {
  if (draft.mode === "line") {
    return createLineFeature(id, draft.coordinates, label);
  }

  if (draft.mode === "polygon") {
    return createPolygonFeature(id, draft.coordinates, label);
  }

  if (draft.mode !== "circle" || !draft.edge) {
    return null;
  }

  return createCircleFeature(id, draft.center, getDistanceMeters(draft.center, draft.edge), label);
}

export function getDraftPointCount(draft: DrawingDraftState) {
  if (draft.mode === "circle") {
    return draft.edge ? 2 : 1;
  }

  return draft.coordinates.length;
}

export function getDrawingKindLabel(kind: WorkbenchDrawMode) {
  if (kind === "point") {
    return "点标注";
  }

  if (kind === "line") {
    return "线标注";
  }

  if (kind === "circle") {
    return "圆形标注";
  }

  return "范围标注";
}

export function getVisibleFeatureCollection(
  featureCollection: DrawingFeatureCollection,
  hiddenFeatureIds: Set<string>
): DrawingFeatureCollection {
  return {
    type: "FeatureCollection",
    features: featureCollection.features.filter((feature) => !hiddenFeatureIds.has(feature.properties.id))
  };
}

export function formatDrawingTime(value: string) {
  return new Intl.DateTimeFormat("zh-CN", {
    hour: "2-digit",
    minute: "2-digit"
  }).format(new Date(value));
}
