package com.changhu.support.fastjson2.serializer;

import com.alibaba.fastjson2.JSONWriter;
import com.alibaba.fastjson2.writer.ObjectWriter;
import com.changhu.common.utils.GeometryUtil;
import org.geotools.measure.Latitude;
import org.geotools.measure.Longitude;
import org.locationtech.jts.geom.Coordinate;
import org.locationtech.jts.geom.Point;

import java.lang.reflect.Type;
import java.util.Arrays;

/**
 * author: luozhun
 * desc: PointSerializer
 * createTime: 2023/8/26 15:59
 */
public class PointSerializer implements ObjectWriter<Point> {

    public static final PointSerializer instance = new PointSerializer();

    private PointSerializer() {
    }

    @Override
    public void write(JSONWriter jsonWriter, Object object, Object fieldName, Type fieldType, long features) {
        if (object == null) {
            jsonWriter.writeNull();
            return;
        }
        Point point = (Point) object;
        if (GeometryUtil.equals(GeometryUtil.emptyPoint(), point)) {
            jsonWriter.writeNull();
            return;
        }
        jsonWriter.writeAny(
                Arrays.asList(
                        new Longitude(point.getCoordinate().getOrdinate(Coordinate.X)).degrees(),
                        new Latitude(point.getCoordinate().getOrdinate(Coordinate.Y)).degrees()
                )
        );
    }
}

