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

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.datatype.joda.cfg.JacksonJodaDateFormat;
import com.fasterxml.jackson.datatype.joda.ser.JodaDateSerializerBase;
import org.joda.time.Duration;
import ru.yandex.webmaster3.core.util.joda.DurationSerializationUtil;

import java.io.IOException;

/**
 * @author avhaliullin
 */
public class WebmasterDurationSerializer extends JodaDateSerializerBase<Duration> {

    public WebmasterDurationSerializer(JacksonJodaDateFormat formatter) {
        super(Duration.class, formatter, false,
                SerializationFeature.WRITE_DURATIONS_AS_TIMESTAMPS);
    }

    @Override
    public WebmasterDurationSerializer withFormat(JacksonJodaDateFormat formatter) {
        return (_format == formatter) ? this : new WebmasterDurationSerializer(formatter);
    }

    // @since 2.5
    @Override
    public boolean isEmpty(SerializerProvider prov, Duration value) {
        return (value.getMillis() == 0L);
    }

    @Override
    public void serialize(Duration value, JsonGenerator gen, SerializerProvider provider) throws IOException {
//        if (_useTimestamp(provider)) {
//            gen.writeNumber(value.getMillis());
//        } else {
        gen.writeString(DurationSerializationUtil.serializeDuration(value));
//        }
    }
}
