package ru.yandex.webmaster.common.tvm;

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

import org.apache.commons.io.IOUtils;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Required;

import ru.yandex.passport.tvmauth.Version;

/**
 * Created by aleksart on 26.06.17.
 */

public class TVM2RefreshKeyService {

    private String tvmApiUrl;

    private static final String tvmVersion = Version.get();
    private static final Logger log = LoggerFactory.getLogger(TVM2RefreshKeyService.class);

    private CloseableHttpClient httpClient;


    public void init(){
        int socketTimeoutMs = 1000;
        int connectTimeoutMs = 500;

        RequestConfig requestConfig = RequestConfig.custom()
                .setSocketTimeout(socketTimeoutMs)
                .setConnectTimeout(connectTimeoutMs)
                .build();
        httpClient = HttpClients.custom()
                .setDefaultRequestConfig(requestConfig)
                .setConnectionTimeToLive(30, TimeUnit.SECONDS)
                .build();
    }

    public String getTvmKeys() {

        HttpGet get = new HttpGet(tvmApiUrl  + "/2/keys/?lib_version=" + tvmVersion);
        try (CloseableHttpResponse response = httpClient.execute(get)) {
            if (response.getStatusLine().getStatusCode() == 200) {
                return IOUtils.toString(response.getEntity().getContent(), Charset.defaultCharset());
            } else {
                String responseString = IOUtils.toString(response.getEntity().getContent(), Charset.defaultCharset());
                if (response.getStatusLine().getStatusCode() / 100 == 4) {
                    log.error("TVM reported client error " + response.getStatusLine() + ". Response:\n" + responseString);
                    return null;
                } else {
                    throw new RuntimeException("Unable to send metrics to Solomon: http code " + response.getStatusLine() +
                            ". Response:\n" + responseString);
                }
            }
        } catch (IOException e) {
            throw new RuntimeException("Unexpected response from TVM", e);
        }

    }

    @Required
    public void setTvmApiUrl(String tvmApiUrl) {
        this.tvmApiUrl = tvmApiUrl;
    }
}
