package ru.yandex.direct.api.v5.exeptiontranslator;

import com.yandex.direct.api.v5.general.ApiExceptionMessage;
import org.springframework.core.annotation.Order;

import ru.yandex.direct.api.v5.ws.exceptionresolver.ExceptionTranslator;
import ru.yandex.direct.common.TranslationService;
import ru.yandex.direct.i18n.Translatable;
import ru.yandex.direct.tracing.Trace;

@Order(ExceptionTranslator.NON_DEFAULT_TRANSLATOR_ORDER)
public abstract class AbstractApiExceptionTranslator implements ExceptionTranslator {

    private final TranslationService translationService;

    protected AbstractApiExceptionTranslator(TranslationService translationService) {
        this.translationService = translationService;
    }

    protected ApiWebFaultException createFault(int code, String shortMessage, String detailedMessage) {
        ApiExceptionMessage apiExceptionMessage = new ApiExceptionMessage()
                .withErrorCode(code)
                .withErrorDetail(detailedMessage)
                .withRequestId(getRequestId());
        return new ApiWebFaultException(shortMessage, apiExceptionMessage);
    }

    protected ApiWebFaultException createFault(int code, Translatable shortMessage, Translatable detailedMessage) {
        return createFault(code, translate(shortMessage), translate(detailedMessage));
    }

    protected ApiWebFaultException createFault(int code, Translatable shortMessage) {
        return createFault(code, translate(shortMessage), "");
    }

    private String translate(Translatable translatable) {
        return translationService.translate(translatable);
    }

    protected String getRequestId() {
        return String.valueOf(Trace.current().getSpanId());
    }
}
