package com.liquidnet.commons.lang.util;

import org.bson.Document;
import org.bson.json.Converter;
import org.bson.json.JsonWriterSettings;
import org.bson.json.StrictJsonWriter;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;

public class BsonUtil {
    private static final JsonWriterSettings build = JsonWriterSettings.builder().dateTimeConverter(new Converter<Long>() {
        @Override
        public void convert(Long aLong, StrictJsonWriter strictJsonWriter) {
//            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
            if (aLong >= -59014396800000L && aLong <= 253399536000000L) {
                strictJsonWriter.writeRaw(String.format("\"%s\"", dateFormat.format(new Date(aLong))));
            } else {
                strictJsonWriter.writeRaw(String.format("new Date(%d)", aLong));
            }
        }
    }).build();

    public static <T> T toBean(Document document, Class<T> clzss){
        return JsonUtils.fromJson(document.toJson(build), clzss);
    }
}
