package be.iminds.ilabt.jfed.experimenter_gui.util;

import be.iminds.ilabt.jfed.ApplicationParametersModule;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.inject.Inject;
import javax.inject.Singleton;
import java.util.Map;

@Singleton
public class ConnectivityDetector {
    private static final Logger LOG = LoggerFactory.getLogger(ConnectivityDetector.class);

    private boolean noInternet;
    private Boolean forceNoInternet = null;

    @Inject
    public ConnectivityDetector(ApplicationParametersModule.ApplicationParameters applicationParameters) {
        this.noInternet = false;

        if (applicationParameters != null) {
            Map<String, String> params = applicationParameters.getParameters();
            String paramKey = "no-internet";
            if (params.containsKey(paramKey)) {
                setNoInternet(true);
                LOG.debug("Parameter " + paramKey + " set: will avoid using internet.");
            } else
                LOG.debug("Parameter " + paramKey + " not set: will assume there is internet connectivity.");
                LOG.debug("Parameters set: " + params);
        } else
            LOG.debug("ConnectivityDetector received no ApplicationParameters");
    }

    public boolean isNoInternet() {
        boolean res = forceNoInternet != null ? forceNoInternet : noInternet;
        LOG.debug("isNoInternet() = "+res);
        return res;
    }

    /**
     * Set if there is internet or not.
     * Typically called by code that detects there is no internet, to report this.
     *
     * Also set called from startup parameters.
     */
    public void setNoInternet(boolean noInternet) {
        this.noInternet = noInternet;
    }

    /** register an explicit user override (typically in GUI) */
    public void forceNoInternet(boolean forceNoInternet) {
        this.forceNoInternet = forceNoInternet;
        LOG.debug("forceNoInternet = "+forceNoInternet);
    }
}
