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

import org.hamcrest.Matcher;
import ru.yandex.autotests.directapi.darkside.exceptions.DarkSideException;
import ru.yandex.autotests.directapi.darkside.model.bmapi.request.BmapiRequest;
import ru.yandex.autotests.directapi.darkside.model.bmapi.request.YmlCatalog;
import ru.yandex.autotests.directapi.darkside.model.bmapi.response.BmapiResponse;
import ru.yandex.autotests.directapi.darkside.steps.base.BaseHttpSteps;
import ru.yandex.autotests.irt.testutils.json.JsonUtils;
import ru.yandex.qatools.allure.annotations.Step;
import ru.yandex.qatools.elliptics.ElAction;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import java.io.StringWriter;
import java.util.regex.Pattern;

import static org.hamcrest.Matchers.equalTo;
import static ru.yandex.autotests.irt.testutils.allure.TestSteps.assertThat;
import static ru.yandex.qatools.elliptics.ElClient.elliptics;

/**
 * Created by pavryabov on 04.08.15.
 */
public class BmapiSteps extends BaseHttpSteps {

    @Step("Вызов ручки из bmapi")
    public BmapiResponse getBmapiResponse(BmapiRequest request) {
        String response = executeMethodExpectReturnCode("", request, 200);
        return JsonUtils.getObject(response, BmapiResponse.class);
    }

    @Step("Вызов ручки из bmapi")
    public String getResponseAsString(BmapiRequest request) {
        return executeMethodExpectReturnCode("", request, 200);
    }

    public void checkCountInYml2Filtered(BmapiRequest request, Integer expectedCount) {
        String response = getResponseAsString(request);
        String expectedResponse = String.format("count:%s\n", expectedCount);
        assertThat("в ответе yml2filtered правильное число товаров", response, equalTo(expectedResponse));
    }

    public void checkCountInYml2Filtered(BmapiRequest request, Matcher matcherForCount) {
        String response = getResponseAsString(request);
        Integer result = 0;
        java.util.regex.Matcher matcher = Pattern.compile("(\\d+)").matcher(response);
        if (matcher.find()) {
            result = Integer.parseInt(matcher.group());
        } else {
            throw new DarkSideException("Ручка yml2filtered вернула неправильный ответ");
        }
        assertThat("в ответе yml2filtered ожидаемое число товаров", result, matcherForCount);
    }

    @Step("запись фида в эллиптикс")
    public String saveFeedToElliptics(String feed, String name) {
        try {
            ElAction result = elliptics()
                    .indefinitely()
                    .path("bmapitest/feeds/")
                    .name(name)
                    .update(feed);
            String url = result.get().url();
            return url.replaceAll("aqua.yandex-team.ru/storage", "qa-storage.yandex-team.ru");
        } catch (Exception e) {
            throw new DarkSideException("Ошибка записи фида в элиптикс", e);
        }
    }

    public String ymlCatalogToXmlString(YmlCatalog ymlCatalog) {
        try {
            JAXBContext jaxbContext = JAXBContext.newInstance(YmlCatalog.class);
            Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
            // output pretty printed
            jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
            StringWriter stringWriter = new StringWriter();
            jaxbMarshaller.marshal(ymlCatalog, stringWriter);
            return stringWriter.toString();
        } catch (JAXBException e) {
            throw new DarkSideException("Ошибка формирования xml из объекта", e);
        }
    }
}
