package cz.senslog.connector.fetch.fieldclimate;

import cz.senslog.connector.fetch.api.ConnectorFetchProvider;
import cz.senslog.connector.fetch.api.ConnectorFetcher;
import cz.senslog.connector.fetch.api.ExecutableFetcher;
import cz.senslog.connector.model.config.DefaultConfig;
import cz.senslog.connector.fetch.fieldclimate.auth.AuthConfig;
import cz.senslog.connector.fetch.fieldclimate.auth.AuthenticationService;
import cz.senslog.connector.model.fieldclimate.FieldClimateModel;
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 final class ConnectorFetchFieldClimateProvider implements ConnectorFetchProvider {

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

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

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

        logger.debug("Getting a configuration for authentication.");
        AuthConfig authConfig = config.getAuthentication();

        logger.info("Initialization a new Azure authentication service.");
        AuthenticationService authService = new AuthenticationService(authConfig);

        logger.debug("Creating a new instance of {}.", FieldClimateFetcher.class);
        FieldClimateFetcher fetcher = new FieldClimateFetcher(config, authService, newHttpSSLClient());
        logger.info("Fetcher for {} was created successfully.", FieldClimateFetcher.class);

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

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

        return executor;
    }
}
