package com.kamco.cd.kamcoback.common.utils.geometry;

import com.fasterxml.jackson.core.JacksonException;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.deser.std.StdDeserializer;
import java.io.IOException;
import org.locationtech.jts.geom.Geometry;
import org.locationtech.jts.io.geojson.GeoJsonReader;
import org.springframework.util.StringUtils;

public class GeometryDeserializer<T extends Geometry> extends StdDeserializer<T> {

  public GeometryDeserializer(Class<T> targetType) {
    super(targetType);
  }

  // TODO: test code
  @SuppressWarnings("unchecked")
  @Override
  public T deserialize(JsonParser jsonParser, DeserializationContext deserializationContext)
      throws IOException, JacksonException {
    String json = jsonParser.readValueAsTree().toString();

    if (!StringUtils.hasText(json)) {
      return null;
    }

    try {
      GeoJsonReader reader = new GeoJsonReader();
      return (T) reader.read(json);
    } catch (Exception e) {
      throw new IllegalArgumentException("Failed to deserialize GeoJSON into Geometry", e);
    }
  }
}
