package sgc.portal.base.format;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;

import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

public class DateJsonSerializer extends JsonSerializer<Date> {
    private final DateFormat format;

    public DateJsonSerializer() {
        this(new SimpleDateFormat("yyyyMMdd"));
    }

    public DateJsonSerializer(DateFormat format) {
        this.format = format;
    }

    @Override
    public void serialize(Date value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
        if (value != null) {
            gen.writeString(format.format(value));
        }
    }

    @Override
    public Class<Date> handledType() {
        return Date.class;
    }
}
