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

import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.ParametersAreNonnullByDefault;
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 com.fasterxml.jackson.databind.ObjectMapper;

import ru.yandex.autotests.directapi.darkside.clients.IntapiJsonRestClient;
import ru.yandex.autotests.directapi.darkside.connection.DarksideConfig;
import ru.yandex.autotests.directapi.darkside.steps.base.BaseIntApiSteps;
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 ru.yandex.qatools.allure.annotations.Step;

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

@ParametersAreNonnullByDefault
public class BsExportSteps extends BaseIntApiSteps<IntapiJsonRestClient> {
    private static final String SERVICE_NAME = "bsexport";
    private static final String ADD_TO_FULL_EXPORT_METHOD_NAME = "add-campaigns-to-full-export-queue";
    private static final String LEGACY_LOGS_METHOD_NAME = "legacyLogs";

    private WebTarget service;
    private LogSteps log = LogSteps.getLogger(this.getClass());

    private IntapiJsonRestClient client;

    public BsExportSteps() {}

    public BsExportSteps(IntapiJsonRestClient client) {
        this.client = client;
    }

    @Override
    public void init(DarksideConfig context) {
        super.init(context);
        if(client == null) {
            setClient(new IntapiJsonRestClient(context));
        } else {
            setClient(client);
        }
        service = client().initClient(SERVICE_NAME);
    }

    private String performRequest(String method, Object request) {
        String jsonRequest = JsonUtils.toString(request);
        Response response = service
                .path(method)
                .request()
                .post(Entity.entity(jsonRequest, MediaType.APPLICATION_JSON));
        assumeThat("Вызов метода " + method + " успешен", response.getStatus(), equalTo(200));
        String jsonResponse = response.readEntity(String.class);
        AllureUtils.addJsonAttachment(SERVICE_NAME + ":" + method + ":Request", jsonRequest);
        AllureUtils.addJsonAttachment(SERVICE_NAME + ":" + method + ":Response", jsonResponse);
        return jsonResponse;
    }

    @Step("Добавляем кампанию {0} в очередь ре-экспорта")
    public void addCampaignToFullExportQueue(Long campaignId) {
        List<Long> campaignIds = Collections.singletonList(campaignId);
        performRequest(ADD_TO_FULL_EXPORT_METHOD_NAME, campaignIds);
        log.info("имитирована одна итерация мастер-процесса ре-экспорта для кампании " + campaignId
                + ", в очередь добавлена запись");
    }

    @Step("Берем логи из БК по uuids {0} и isOmitMdsMeta {1}")
    public Map getBSLogs(String[] uuid, boolean isOmitMdsMeta) {
        Response response = service
                .path(LEGACY_LOGS_METHOD_NAME)
                .queryParam("omitMdsMeta", String.valueOf(isOmitMdsMeta))
                .queryParam("uuid", uuid)
                .request()
                .get();
        assumeThat("Вызов метода " + LEGACY_LOGS_METHOD_NAME + " успешен", response.getStatus(), equalTo(200));
        String jsonResponse = response.readEntity(String.class);
        AllureUtils.addJsonAttachment(SERVICE_NAME + ":" + LEGACY_LOGS_METHOD_NAME + ":Request", jsonResponse);
        try {
            return new ObjectMapper().readValue(jsonResponse, HashMap.class);
        } catch (Exception e) {
            throw new IllegalArgumentException(e);
        }
    }
}
