package ru.yandex.direct.integrations.configuration;

import java.time.Duration;

import org.apache.http.client.HttpClient;

import ru.yandex.direct.blackbox.client.BlackboxClient;
import ru.yandex.direct.config.DirectConfig;
import ru.yandex.inside.passport.blackbox2.Blackbox2;
import ru.yandex.inside.passport.blackbox2.BlackboxRawRequestExecutor;
import ru.yandex.inside.passport.blackbox2.BlackboxRequestExecutorWithRetries;
import ru.yandex.misc.io.http.Timeout;
import ru.yandex.misc.io.http.apache.v4.ApacheHttpClientUtils;

public class IntegrationsUtils {
    public static BlackboxClient configureBlackboxClient(DirectConfig directConfig,
                                                         String configBranch,
                                                         int maxConnections) {
        DirectConfig cfg = directConfig.getBranch(configBranch);

        String blackboxUrl = cfg.getString("endpoint");
        Duration blackboxTimeout = cfg.findDuration("timeout")
                .orElse(Duration.ofSeconds(2));
        int blackboxRetries = cfg.findInt("retries")
                .orElse(3);

        Timeout timeout = Timeout.milliseconds(blackboxTimeout.toMillis());
        HttpClient httpClient = ApacheHttpClientUtils.multiThreadedClient(timeout, maxConnections);
        BlackboxRawRequestExecutor rawExecuter = new BlackboxRawRequestExecutor(blackboxUrl, httpClient);
        BlackboxRequestExecutorWithRetries executorWithRetries =
                new BlackboxRequestExecutorWithRetries(rawExecuter, blackboxRetries);

        Blackbox2 blackbox2 = new Blackbox2(executorWithRetries);
        return new BlackboxClient(blackbox2);
    }
}
