package eu.eudat.logic.utilities.json;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.deser.std.StdDeserializer;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

public class MultiDateDeserializer extends StdDeserializer<Date> {

    private static final List<String> DATE_FORMATS = Arrays.asList("yyyy-MM-dd'T'HH:mm:ss'Z'", "yyyy-MM-dd'T'HH:mm:ss.S");


    public MultiDateDeserializer() {
        super(Date.class);
    }

    protected MultiDateDeserializer(Class<?> vc) {
        super(vc);
    }

    @Override
    public Date deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {
        String text = p.getText();

        for (String dateFormat: DATE_FORMATS) {
            try {
                return new SimpleDateFormat(dateFormat).parse(text);
            } catch (ParseException ignored) {
            }
        }
        throw new JsonParseException(p, "No supported Date format");
    }
}
