package cz.senslog.connector.fetch.alapans;

import cz.senslog.connector.fetch.api.ConnectorFetcher;
import cz.senslog.connector.fetch.api.ExecutableFetcher;
import cz.senslog.connector.model.alapans.AlapansModel;
import cz.senslog.connector.model.config.DefaultConfig;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import static cz.senslog.connector.tools.http.HttpClient.newHttpClient;
import static cz.senslog.connector.tools.http.HttpClient.newHttpSSLClient;

public class ConnectorFetchAlapansProvider implements cz.senslog.connector.fetch.api.ConnectorFetchProvider {

    private static final Logger logger = LogManager.getLogger(ConnectorFetchAlapansProvider.class);

    @Override
    public ExecutableFetcher<AlapansModel> createExecutableFetcher(DefaultConfig defaultConfig) {
        logger.info("Initialization a new fetch provider {}.", ConnectorFetchAlapansProvider.class);

        logger.debug("Creating a new configuration.");
        AlapansConfig config = new AlapansConfig(defaultConfig);
        logger.info("Configuration for {} was created successfully.", ConnectorFetcher.class);

        logger.debug("Creating a new instance of {}.", AlapansFetcher.class);
        AlapansFetcher fetcher = new AlapansFetcher(config, newHttpSSLClient());

        logger.debug("Getting a configuration for proxy session.");
        AlapansSessionProxyConfig proxyConfig = config.getSessionProxy();

        ExecutableFetcher<AlapansModel> executor;
        if (proxyConfig != null) {
            logger.debug("Creating a new instance of {}.", AlapansProxySession.class);
            AlapansProxySession proxySession = new AlapansProxySession(fetcher, proxyConfig, newHttpClient());
            logger.info("Fetcher session for {} was created successfully.", AlapansProxySession.class);
            executor = ExecutableFetcher.createWithProxySession(proxySession);
        } else {
            executor = ExecutableFetcher.create(fetcher);
        }
        logger.info("Fetcher executor for {} was created successfully.", AlapansFetcher.class);

        return executor;
    }
}
