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

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.std.StdSerializer;
import java.io.IOException;
import java.util.Objects;
import org.locationtech.jts.geom.Geometry;
import org.locationtech.jts.io.geojson.GeoJsonWriter;

public class GeometrySerializer<T extends Geometry> extends StdSerializer<T> {

  // TODO: test code
  public GeometrySerializer(Class<T> targetType) {
    super(targetType);
  }

  @Override
  public void serialize(
      T geometry, JsonGenerator jsonGenerator, SerializerProvider serializerProvider)
      throws IOException {
    if (Objects.nonNull(geometry)) {
      // default: 8자리 강제로 반올림시킴. 16자리로 늘려줌
      GeoJsonWriter writer = new GeoJsonWriter(16);
      String json = writer.write(geometry);
      jsonGenerator.writeRawValue(json);
    } else {
      jsonGenerator.writeNull();
    }
  }
}
