using Manager.DTOs; using NetTopologySuite; using NetTopologySuite.Geometries; using System.Collections.Generic; using System.Linq; using System.Text.Json; using System; namespace ManagerService.Helpers { public static class GeometryMapper { public static GeometryDTO ToDto(this Geometry geometry) { return geometry switch { Point point => new GeometryDTO { type = "Point", coordinates = new List { point.X, point.Y } }, LineString line => new GeometryDTO { type = "LineString", coordinates = line.Coordinates .Select(coord => new List { coord.X, coord.Y }) .ToList() }, Polygon polygon => new GeometryDTO { type = "Polygon", coordinates = new List>> { polygon.ExteriorRing.Coordinates .Select(coord => new List { coord.X, coord.Y }) .ToList() } }, _ => throw new NotSupportedException($"Geometry type {geometry.GeometryType} not supported.") }; } public static Geometry FromDto(this GeometryDTO dto, GeometryFactory factory = null!) { factory ??= NtsGeometryServices.Instance.CreateGeometryFactory(); return dto.type switch { "Point" => CreatePoint(dto, factory), "LineString" => CreateLineString(dto, factory), "Polygon" => CreatePolygon(dto, factory), _ => throw new NotSupportedException($"DTO type {dto.type} not supported.") }; } private static Point CreatePoint(GeometryDTO dto, GeometryFactory factory) { var coords = ((JsonElement)dto.coordinates).Deserialize>(); return factory.CreatePoint(new Coordinate(coords[0], coords[1])); } private static LineString CreateLineString(GeometryDTO dto, GeometryFactory factory) { var coords = ((JsonElement)dto.coordinates).Deserialize>>(); var coordinates = coords.Select(c => new Coordinate(c[0], c[1])).ToArray(); return factory.CreateLineString(coordinates); } private static Polygon CreatePolygon(GeometryDTO dto, GeometryFactory factory) { var rings = ((JsonElement)dto.coordinates).Deserialize>>>(); var exterior = rings.First().Select(c => new Coordinate(c[0], c[1])).ToArray(); return factory.CreatePolygon(exterior); } } }