package com.atlassian.bitbucket;

import com.atlassian.bitbucket.i18n.KeyedMessage;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;

import static com.google.common.base.Preconditions.checkNotNull;

public abstract class ServiceException extends RuntimeException {

    private static final long serialVersionUID = -5270791443693616427L;

    private final String localizedMessage;
    private final String messageKey;

    private transient KeyedMessage keyedMessage;

    public ServiceException(@Nonnull KeyedMessage message) {
        this(message, null);
    }

    public ServiceException(@Nonnull KeyedMessage message, @Nullable Throwable cause) {
        super(checkNotNull(message, "message").getRootMessage(), cause);

        this.localizedMessage = message.getLocalisedMessage();
        this.messageKey = message.getKey();

        keyedMessage = message;
    }

    @Nonnull
    public KeyedMessage getKeyedMessage() {
        if (keyedMessage == null) {
            //We may have been serialised and lost the message; reconstruct it
            keyedMessage = new KeyedMessage(messageKey, localizedMessage, getMessage());
        }

        return keyedMessage;
    }

    @Nonnull
    @Override
    public String getLocalizedMessage() {
        return localizedMessage;
    }

    @Nonnull
    public String getMessageKey() {
        return messageKey;
    }
}
