// Copyright (c) 2020 UWB & LESP.
// The UWB & LESP license this file to you under the MIT license.

package cz.senslog.connector.fetch.senslog.v1;

import cz.senslog.connector.fetch.api.ConnectorFetchProvider;
import cz.senslog.connector.fetch.api.ExecutableFetcher;
import cz.senslog.connector.model.config.DefaultConfig;
import cz.senslog.connector.model.v1.SenslogV1Model;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

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

public class SenslogFetchProvider implements ConnectorFetchProvider {

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

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

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


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

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

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

        return executor;
    }
}
