package ru.yandex.autotests.direct.intapi.java.core;

import okhttp3.ResponseBody;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import retrofit2.Call;
import retrofit2.Converter;
import retrofit2.Response;
import ru.yandex.autotests.direct.intapi.models.ErrorResponse;
import ru.yandex.autotests.direct.utils.BaseSteps;
import ru.yandex.autotests.irt.testutils.allure.AllureUtils;
import ru.yandex.qatools.allure.annotations.Step;

import java.io.IOException;
import java.lang.annotation.Annotation;

public abstract class DirectJavaIntapiBaseSteps<T> extends BaseSteps<DirectJavaIntapiStepsContext> {
    private Logger logger;
    protected T apiService;
    private Class<T> apiServiceClass;

    public DirectJavaIntapiBaseSteps(Class<T> apiServiceClass) {
        this.apiServiceClass = apiServiceClass;
        logger = LoggerFactory.getLogger(DirectJavaIntapiBaseSteps.class);
    }

    protected T getApiService() {
        return getContext().getApiClient().createService(apiServiceClass);
    }

    @Step("Intapi call:")
    protected <R> Response<R> execute(Call<R> call) {
        Response<R> result = null;
        try {
            result = call.execute();
        } catch (IOException e) {
            throw new DirectJavaIntapiError("Exception while processing intapi request", e);
        }
        return result;
    }

    protected <R> Response<R> executeSafe(Call<R> call) {
        Response<R> response = execute(call);
        if (!response.isSuccessful()) {
            throw new DirectJavaIntapiError("Intapi returned error: " + response.message());
        }
        return response;
    }

    protected <R> Converter<ResponseBody, R> getConverter(Class<R> toClass) {
        return getContext().getApiClient().getAdapterBuilder().build()
                .responseBodyConverter(toClass, new Annotation[0]);
    }

}
