package cd.casic.framework.commons.util.json.databind;

import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.BeanProperty;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.ContextualSerializer;

import java.io.IOException;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;

/**
 * 基于时间戳的 LocalDateTime 序列化器
 *
 * @author 老五
 */
public class TimestampLocalDateTimeSerializer extends JsonSerializer<LocalDateTime> implements ContextualSerializer {

    public static final TimestampLocalDateTimeSerializer INSTANCE = new TimestampLocalDateTimeSerializer();
    private DateTimeFormatter dateTimeFormatter = null;

    public TimestampLocalDateTimeSerializer() {
    }

    public TimestampLocalDateTimeSerializer(DateTimeFormatter dateTimeFormatter) {
        this.dateTimeFormatter = dateTimeFormatter;
    }

    @Override
    public void serialize(LocalDateTime value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
//        // 将 LocalDateTime 对象，转换为 Long 时间戳
//        gen.writeNumber(value.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli());
        if (dateTimeFormatter != null) {
            gen.writeString(value.format(dateTimeFormatter));
        } else {
            gen.writeNumber(value.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli());
        }
    }

    @Override
    public JsonSerializer<?> createContextual(SerializerProvider serializerProvider, BeanProperty property) throws JsonMappingException {
        if (property != null) {
            JsonFormat format = property.getAnnotation(JsonFormat.class);
            if (format != null && !format.pattern().isEmpty()) {
                DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(format.pattern());
                return new TimestampLocalDateTimeSerializer(dateTimeFormatter);
            }
        }
        return this;
    }
}
