package ru.yandex.qe.bus.exception;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;

import ru.yandex.qe.json.JsonUtils;

class JsonException {
    String type;
    List<String> message;
    JsonException cause;

    @JsonCreator
    private JsonException(@JsonProperty("type") String type,
                          @JsonProperty("message") List<String> message,
                          @JsonProperty("cause") JsonException cause) {
        this.type = type;
        this.message = message;
        this.cause = cause;
    }

    public String asString() {
        return JsonUtils.write(this);
    }

    public static JsonException fromString(String json) {
        return JsonUtils.read(json, JsonException.class);
    }

    public static JsonException fromThrowable(Throwable e) {
        return new JsonException(e.getClass().getName(), split(e.getMessage()),
                e.getCause() != null ? fromThrowable(e.getCause()) : null);
    }

    private static List<String> split(String message) {
        return message == null ? Collections.emptyList()
                : Arrays.asList(message.split("\\n"));
    }

    public String getType() {
        return type;
    }

    public List<String> getMessage() {
        return message;
    }

    public JsonException getCause() {
        return cause;
    }
}
