package ru.yandex.webmaster3.storage.util;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.jdk8.Jdk8Module;
import com.fasterxml.jackson.datatype.joda.JodaModule;
import com.fasterxml.jackson.module.paramnames.ParameterNamesModule;
import ru.yandex.webmaster3.core.WebmasterException;
import ru.yandex.webmaster3.core.http.WebmasterErrorResponse;
import ru.yandex.webmaster3.core.http.WebmasterJsonModule;
import ru.yandex.webmaster3.core.util.joda.jackson.WebmasterDurationModule;

import java.io.IOException;

/**
 * Стоит попробовать использовать единый ObjectMapper для работы с БД
 *
 * @author avhaliullin
 */
//TODO: Удалить данный экземпляр и поменять на JsonMapping, они идентичные.
public class JsonDBMapping {
    public static final ObjectMapper OM = new ObjectMapper()
            .registerModule(new WebmasterJsonModule(false))
            .registerModule(new JodaModule())
            .registerModule(new ParameterNamesModule())
            .registerModule(new WebmasterDurationModule(true))
            .registerModule(new Jdk8Module())
            .setSerializationInclusion(JsonInclude.Include.ALWAYS)
            .disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)
            .disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);

    public static <T> String writeValueAsString(T object) {
        try {
            return OM.writeValueAsString(object);
        } catch (JsonProcessingException e) {
            throw new WebmasterException("Json mapping error",
                    new WebmasterErrorResponse.InternalUnknownErrorResponse(JsonDBMapping.class, "Json mapping error"), e);
        }
    }

    public static <T> T readValue(String s, Class<T> clazz) {
        try {
            return OM.readValue(s, clazz);
        } catch (IOException e) {
            throw new WebmasterException("Json mapping error",
                    new WebmasterErrorResponse.UnableToReadJsonRequestResponse(JsonDBMapping.class, e), e);
        }
    }
}
