package ru.yandex.autotests.directapi.darkside.steps.base;


import java.util.Arrays;

import javax.ws.rs.client.Entity;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import ru.yandex.autotests.directapi.darkside.clients.IntapiJsonRestClient;
import ru.yandex.autotests.directapi.darkside.connection.DarksideConfig;
import ru.yandex.autotests.directapi.darkside.datacontainers.jsonrpc.balanceclient.BalanceClientJSONResponse;
import ru.yandex.autotests.irt.testutils.allure.AllureUtils;
import ru.yandex.autotests.irt.testutils.allure.LogSteps;
import ru.yandex.autotests.irt.testutils.json.JsonUtils;

import static org.hamcrest.Matchers.equalTo;
import static ru.yandex.autotests.irt.testutils.allure.TestSteps.assumeThat;

/**
 * Базовый класс для степов методов, работающих по json-rest
 */
public abstract class BaseJsonRestSteps<T> extends BaseIntApiSteps<IntapiJsonRestClient> {
    private LogSteps log = LogSteps.getLogger(this.getClass());
    private WebTarget service;

    @Override
    public void init(DarksideConfig context) {
        super.init(context);
        setClient(new IntapiJsonRestClient(context));
        service = client().initClient(getServiceName(), getMethodName());
    }

    protected BalanceClientJSONResponse performRequest(Object request) {
        return performRequest(request, 200);
    }

    protected BalanceClientJSONResponse performRequest(Object request, int expectedHttpCode) {
        String jsonRequest = JsonUtils.toString(Arrays.asList(request));
        Response response = service()
                .request()
                .post(Entity.entity(jsonRequest, MediaType.APPLICATION_JSON));
        assumeThat("Получен ответ с кодом " + expectedHttpCode, response.getStatus(), equalTo(expectedHttpCode));
        String jsonResponse = response.readEntity(String.class);
        AllureUtils.addJsonAttachment(getServiceName() + ":" + getMethodName() + ":Request", jsonRequest);
        AllureUtils.addJsonAttachment(getServiceName() + ":" + getMethodName() + ":Response", jsonResponse);
        return new BalanceClientJSONResponse(JsonUtils.getObject(jsonResponse, String[].class));
    }


    protected WebTarget service() {
        return service;
    }

    protected LogSteps log() {
        return log;
    }

    protected abstract String getServiceName();

    protected abstract String getMethodName();
}
