package com.kamco.cd.kamcoback.Innopam.utils;

import com.fasterxml.jackson.databind.JsonNode;
import org.locationtech.jts.geom.Coordinate;
import org.locationtech.jts.geom.Geometry;
import org.locationtech.jts.geom.GeometryFactory;
import org.locationtech.jts.geom.LinearRing;
import org.locationtech.jts.geom.MultiPolygon;
import org.locationtech.jts.geom.Polygon;

public class GeoJsonGeometryConverter {

  private static final GeometryFactory GF = new GeometryFactory();

  public static Geometry toGeometry(JsonNode geomNode) {
    String type = geomNode.path("type").asText();

    if ("Polygon".equals(type)) {
      return toPolygon(geomNode.path("coordinates"));
    }
    if ("MultiPolygon".equals(type)) {
      return toMultiPolygon(geomNode.path("coordinates"));
    }
    return null;
  }

  private static Polygon toPolygon(JsonNode coords) {
    LinearRing shell = GF.createLinearRing(toCoords(coords.get(0)));
    return GF.createPolygon(shell);
  }

  private static MultiPolygon toMultiPolygon(JsonNode coords) {
    Polygon[] polys = new Polygon[coords.size()];
    for (int i = 0; i < coords.size(); i++) {
      polys[i] = toPolygon(coords.get(i));
    }
    return GF.createMultiPolygon(polys);
  }

  private static Coordinate[] toCoords(JsonNode ring) {
    Coordinate[] c = new Coordinate[ring.size() + 1];
    for (int i = 0; i < ring.size(); i++) {
      c[i] = new Coordinate(ring.get(i).get(0).asDouble(), ring.get(i).get(1).asDouble());
    }
    c[c.length - 1] = c[0];
    return c;
  }
}
