package ru.yandex.webmaster3.storage.user;

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.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.storage.user.message.MessageTypeEnum;
import ru.yandex.webmaster3.storage.user.message.content.MessageContent;

import java.io.IOException;

/**
 * @author avhaliullin
 */
public class MessageContentConverter {
    private static final ObjectMapper OM = new ObjectMapper()
            .registerModule(new JodaModule())
            .registerModule(new ParameterNamesModule())
            .registerModule(new WebmasterJsonModule(false))
            .setSerializationInclusion(JsonInclude.Include.NON_NULL)
            .disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);

    public static String serialize(MessageContent messageInfo) {
        try {
            return OM.writeValueAsString(messageInfo);
        } catch (JsonProcessingException e) {
            throw new WebmasterException("Failed to serialize user message of type " + messageInfo.getType(),
                    new WebmasterErrorResponse.InternalUnknownErrorResponse(MessageContentConverter.class,
                            "Failed to serialize user message of type " + messageInfo.getType()),
                    e);
        }
    }

    public static MessageContent deserialize(MessageTypeEnum type, String s) {
        try {
            return OM.readValue(s, type.getMessageClass());
        } catch (IOException e) {
            throw new WebmasterException(
                    "Failed to deserialize user message of type " + type + " from string: " + s,
                    new WebmasterErrorResponse.InternalUnknownErrorResponse(MessageContentConverter.class,
                            "Failed to deserialize user message of type " + type + " from string: " + s),
                    e);
        }
    }
}
