import { BufferGeometry, Vector3 } from "three";
type DXFData = any;
export const convertDXFToThree = (dxfData: DXFData): BufferGeometry[] => {
  const geometries: BufferGeometry[] = [];
  const UNIT = 1000;
  if (dxfData.entities) {
    dxfData.entities.forEach((entity: any) => {
      // LINE
      if (entity.type === "LINE" && entity.vertices) {
        const points = [
          new Vector3(entity.vertices[0].x, entity.vertices[0].y, 0),
          new Vector3(entity.vertices[1].x, entity.vertices[1].y, 0),
        ];
        const geometry = new BufferGeometry().setFromPoints(points);
        geometry.scale(1 / UNIT, 1 / UNIT, 1 / UNIT);
        geometries.push(geometry);
      }

      // LWPOLYLINE
      else if (entity.type === "LWPOLYLINE" && entity.vertices) {
        const points: Vector3[] = entity.vertices.map(
          (v: any) => new Vector3(v.x, v.y, 0)
        );

        for (let i = 0; i < points.length - 1; i++) {
          const segment = [points[i], points[i + 1]];
          const geometry = new BufferGeometry().setFromPoints(segment);
          geometry.scale(1 / UNIT, 1 / UNIT, 1 / UNIT);
          geometries.push(geometry);
        }
      }

      // ARC
      else if (
        entity.type === "ARC" &&
        entity.center &&
        entity.radius !== undefined
      ) {
        const { center, radius, startAngle, endAngle } = entity;
        if (
          center === undefined ||
          radius === undefined ||
          startAngle === undefined ||
          endAngle === undefined
        )
          return;
        const numSegments = 32;
        const points: Vector3[] = [];

        for (let i = 0; i <= numSegments; i++) {
          const t = i / numSegments;
          const angle = startAngle + t * (endAngle - startAngle); // linear interpolation
          const x = center.x + radius * Math.cos(angle);
          const y = center.y + radius * Math.sin(angle);
          points.push(new Vector3(x, y, 0));
        }

        const geometry = new BufferGeometry().setFromPoints(points);
        geometry.scale(1 / UNIT, 1 / UNIT, 1 / UNIT);
        geometries.push(geometry);
      }
    });
  }
  return geometries;
};
