package sgc.portal.base.format;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import org.apache.commons.lang3.StringUtils;

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

public class DateJsonDeserializer extends JsonDeserializer<Date> {
    private final DateFormat format;

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

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

    @Override
    public Date deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {
        try {
            return StringUtils.isNotEmpty(p.getText()) ? format.parse(p.getText()) : null;
        } catch (ParseException e) {
            throw new IOException(e);
        }
    }

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