package ru.yandex.webmaster3.core.turbo;

import java.io.IOException;
import java.nio.charset.Charset;
import java.util.concurrent.TimeUnit;

import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import ru.yandex.webmaster3.core.http.HttpConstants;
import ru.yandex.webmaster3.core.security.tvm.TVMTokenService;
import ru.yandex.webmaster3.core.util.json.JsonMapping;

/**
 * ishalaru
 * 22.07.2020
 **/
@Slf4j
@Service
@RequiredArgsConstructor(onConstructor_ = {@Autowired})
public class TurboIntegrationService {
    private static final int SOCKET_TIMEOUT = 10_000;
    private static final String CMNT_API = "/turbo_url_features/v1/comments";
    @Value("${webmaster3.core.turbo.host}")
    private final String turboUrl;
    private final TVMTokenService turboCmntApiTvmTokenService;


    private CloseableHttpClient httpClient;

    public void init() {

        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectionRequestTimeout(HttpConstants.DEFAULT_CONNECTION_REQUEST_TIMEOUT)
                .setConnectTimeout(HttpConstants.DEFAULT_CONNECT_TIMEOUT)
                .setSocketTimeout(SOCKET_TIMEOUT)
                .build();

        httpClient = HttpClientBuilder.create()
                .setDefaultRequestConfig(requestConfig)
                .setConnectionTimeToLive(10, TimeUnit.MINUTES)
                .build();
    }

    public boolean updateTurboCmntStatus(String url, boolean status) {
        HttpPost httpRequest = new HttpPost(turboUrl + CMNT_API);
        httpRequest.setHeader(TVMTokenService.TVM2_TICKET_HEADER, turboCmntApiTvmTokenService.getToken());
        String data = JsonMapping.writeValueAsString(new TurboCmntData(url, status));
        StringEntity entity = new StringEntity(data, Charset.defaultCharset());
        httpRequest.setEntity(entity);
        try (final CloseableHttpResponse execute = httpClient.execute(httpRequest)) {
            if (log.isTraceEnabled()) {
                log.trace("Result: {}", execute.getStatusLine());
                log.trace("Entity: {}", execute.getEntity());
                log.trace("Response body:{}", new String(execute.getEntity().getContent().readAllBytes(), Charset.defaultCharset()));
            }
            if (execute.getStatusLine().getStatusCode() / 100 == 2) {
                return true;
            }
        } catch (ClientProtocolException e) {
            log.error(e.getMessage(), e);
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        }
        return false;
    }

    @lombok.Value
    public static class TurboCmntData {
        String url;
        @JsonProperty("comments_enabled")
        boolean enable;
    }

}
