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

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.List;
import java.util.Map;

import com.google.common.reflect.TypeToken;
import com.google.gson.Gson;
import retrofit2.Response;

import ru.yandex.autotests.direct.intapi.DisplaycanvascontrollerApi;
import ru.yandex.autotests.direct.intapi.java.core.DirectJavaIntapiBaseSteps;
import ru.yandex.autotests.direct.intapi.java.core.DirectJavaIntapiError;
import ru.yandex.autotests.direct.intapi.models.CreativeCampaignRequest;
import ru.yandex.autotests.direct.intapi.models.CreativeCampaignResult;
import ru.yandex.autotests.direct.intapi.models.CreativeUploadData;
import ru.yandex.autotests.direct.intapi.models.CreativeUploadResponse;
import ru.yandex.autotests.direct.intapi.models.CreativeUploadResult;
import ru.yandex.autotests.direct.intapi.models.ErrorResponse;
import ru.yandex.autotests.direct.intapi.models.GetUsedCreativesResponse;
import ru.yandex.autotests.irt.testutils.allure.AssumptionException;
import ru.yandex.qatools.allure.annotations.Step;

/*
 * todo javadoc
 */
public class DisplayCanvasSteps extends DirectJavaIntapiBaseSteps<DisplaycanvascontrollerApi> {
    public DisplayCanvasSteps() {
        super(DisplaycanvascontrollerApi.class);
    }

    @Step("DisplayCanvas: запрос DisplayCanvas/auth operatorUid [{0}] clientId[{1}]")
    public CreativeUploadResponse uploadCreatives(Long operatorUid, Long clientId, List<CreativeUploadData> creatives) {
        return executeSafe(getApiService().uploadCreatives(operatorUid, clientId, creatives)).body();
    }

    @Step("Intapi: запрос DisplayCanvas/auth operatorUid [{0}] clientId[{1}]. Ожидаем ошибку")
    public ErrorResponse uploadCreativesError(Long operatorUid, Long clientId, List<CreativeUploadData> creatives) {
        Response resp = execute(getApiService().uploadCreatives(operatorUid, clientId, creatives));
        return toErrorResponse(resp);
    }

    @Step("DisplayCanvas: запрос DisplayCanvas/get_creatives_campaigns operatorUid [{0}] clientId[{1}] creativeIds[{2}]")
    public Map<Long, List<CreativeCampaignResult>> getCreativesCampaigns(Long operatorUid, Long clientId,
                                                                         List<Long> creativeIds) {
        return getCreativesCampaigns(operatorUid, clientId, new CreativeCampaignRequest().withCreativeIds(creativeIds));
    }

    @Step("DisplayCanvas: запрос DisplayCanvas/get_creatives_campaigns operatorUid [{0}] clientId[{1}]")
    public Map<Long, List<CreativeCampaignResult>> getCreativesCampaigns(Long operatorUid, Long clientId,
                                                                         CreativeCampaignRequest request) {
        Object objRes = executeSafe(getApiService().getCreativesCampaigns(operatorUid, clientId, request)).body();
        Type type = new TypeToken<Map<Long, List<CreativeCampaignResult>>>() {
        }.getType();
        return new Gson().fromJson(new Gson().toJson(objRes), type);
    }

    @Step("DisplayCanvas: запрос DisplayCanvas/get_used_creatives clientId[{0}] creativeType[{1}]")
    public GetUsedCreativesResponse getCreativesCampaigns(Long clientId, String creativeType) {
        return executeSafe(getApiService().getUsedCreatives(clientId, creativeType, null, null, null)).body();
    }

    public CreativeUploadResult resultById(CreativeUploadResponse response, Long creativeId) {
        return response.getUploadResults().stream()
                .filter(c -> c.getCreativeId().equals(creativeId))
                .findFirst()
                .orElseThrow(() -> new AssumptionException("Не получен результат о сохранении креатива " + creativeId));
    }


    private ErrorResponse toErrorResponse(Response response) {
        if (response.isSuccessful() || response.errorBody() == null) {
            throw new DirectJavaIntapiError("Intapi responses with no error");
        }
        ErrorResponse error = null;
        try {
            error = getConverter(ErrorResponse.class).convert(response.errorBody());
        } catch (IOException e) {
            throw new DirectJavaIntapiError("Cannot parse error responce");
        }
        return error;
    }
}
