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 sgc.portal.base.util.DateTime;

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

public class DateTimeJsonDeserializer extends JsonDeserializer<DateTime> {
    private final DateFormat format;

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

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

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

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