package ru.yandex.webmaster3.core.util.joda.jackson;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonTokenId;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.deser.std.StdScalarDeserializer;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.Duration;
import ru.yandex.webmaster3.core.util.joda.DurationSerializationUtil;

import java.io.IOException;

/**
 * @author avhaliullin
 */
public class WebmasterDurationDeserializer extends StdScalarDeserializer<Duration> {
    private static final long serialVersionUID = 1L;

    private final boolean deserializeCompatible;

    public WebmasterDurationDeserializer(boolean deserializeCompatible) {
        super(Duration.class);
        this.deserializeCompatible = deserializeCompatible;
    }

    @Override
    public Duration deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
        switch (p.getCurrentTokenId()) {
            case JsonTokenId.ID_NUMBER_INT: // assume it's millisecond count
                return new Duration(p.getLongValue());
            case JsonTokenId.ID_STRING:
                return _deserialize(ctxt, p.getText());
            default:
        }
        throw ctxt.mappingException("expected JSON Number or String");
    }

    protected Duration _deserialize(DeserializationContext ctxt, String str)
            throws IOException {
        if (StringUtils.isEmpty(str)) {
            if (ctxt.isEnabled(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT)) {
                return null;
            }
        }
        return deserializeCompatible ? DurationSerializationUtil.deserializeCompatible(str) : DurationSerializationUtil.deserializeDuration(str);
    }
}
