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

import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClientBuilder;

import ru.yandex.autotests.directapi.apiclient.RequestHeader;
import ru.yandex.autotests.directapi.apiclient.config.ConnectionConfig;
import ru.yandex.autotests.directapi.apiclient.config.ProtocolType;
import ru.yandex.autotests.directapi.apiclient.version5.ServiceNames;
import ru.yandex.autotests.directapi.steps.BaseApiSteps;
import ru.yandex.autotests.irt.testutils.allure.LogSteps;
import ru.yandex.qatools.allure.annotations.Step;

public class PingJavaApiSteps extends BaseApiSteps {

    private static final Integer JAVA_SERVICE_RESPONSE_CODE = 405;
    private static final Integer PERL_SERVICE_RESPONSE_CODE = 200;

    private static PingJavaApiSteps _instance;

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

    private PingJavaApiSteps(ConnectionConfig connectionConfig, RequestHeader requestHeader) {
        super(connectionConfig, requestHeader);
    }

    public static PingJavaApiSteps getInstance(ConnectionConfig connectionConfig, RequestHeader requestHeader) {
        if (_instance == null) {
            _instance = new PingJavaApiSteps(connectionConfig, requestHeader);
        } else {
            _instance.setConnectionConfig(connectionConfig);
            _instance.setRequestHeader(requestHeader);
        }
        return _instance;
    }

    @Step("Запрос: переключен ли сервис на Java")
    public boolean isJavaApiUp(ServiceNames service) {
        return JAVA_SERVICE_RESPONSE_CODE.equals(getHttpResponseCode(service));
    }

    @Step("Запрос: возвращает ли Perl-сервис статус OK")
    public boolean isPerlApiUp(ServiceNames service) {
        return PERL_SERVICE_RESPONSE_CODE.equals(getHttpResponseCode(service));
    }

    private Integer getHttpResponseCode(ServiceNames service) {
        HttpClient client = HttpClientBuilder.create().build();
        HttpGet request = new HttpGet(urlFor(service));
        request.setHeader("Authorization", "Bearer " + requestHeader.getToken());
        try {
            int code = client.execute(request).getStatusLine().getStatusCode();
            log.info(String.format("Service %s sent HTTP response code: %s", service, code));
            return code;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    private String urlFor(ServiceNames service) {
        return connectionConfig.getEndPointForV5(ProtocolType.JSON, service.toString());
    }

}
