package be.iminds.jfed.gts_highlevel.controller;

import be.iminds.ilabt.jfed.lowlevel.GeniUserProvider;
import be.iminds.ilabt.jfed.lowlevel.JFedException;
import be.iminds.ilabt.jfed.lowlevel.ApiInfo;
import be.iminds.ilabt.jfed.lowlevel.connection.HandleUntrustedCallback;
import be.iminds.ilabt.jfed.lowlevel.connection.HttpConnection;
import be.iminds.ilabt.jfed.lowlevel.connection.JFedConnection;
import be.iminds.ilabt.jfed.lowlevel.connection.JFedConnectionProvider;
import be.iminds.ilabt.jfed.util.JFedTrustStore;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.inject.Inject;
import java.net.URL;

/**
 * User: twalcari
 * Date: 9/23/2015
 * Time: 09:54
 */
public class GtsConnectionProviderImpl implements GtsConnectionProvider {
    private static final Logger LOG = LoggerFactory.getLogger(GtsConnectionProviderImpl.class);

    private static final HandleUntrustedCallback HANDLE_UNTRUSTED_CALLBACK = sSLCertificateJFedInfo -> {
        LOG.warn("DANGER: Untrusted connection!");
        return true;
    };

    private final URL baseUrl;


    private final JFedTrustStore jFedTrustStore;
    private final GeniUserProvider geniUserProvider;
    private final JFedConnectionProvider connectionProvider;

    @Inject
    public GtsConnectionProviderImpl(URL baseUrl, JFedTrustStore jFedTrustStore,
                                     GeniUserProvider geniUserProvider,
                                     JFedConnectionProvider connectionProvider) {
        this.baseUrl = baseUrl;
        this.jFedTrustStore = jFedTrustStore;
        this.geniUserProvider = geniUserProvider;
        this.connectionProvider = connectionProvider;
    }

    public HttpConnection getConnection() throws JFedException {
        assert geniUserProvider.isUserLoggedIn();
        JFedConnection res = null;
        res = connectionProvider.getConnectionByUrl(jFedTrustStore,
                geniUserProvider.getLoggedInGeniUser(),
                baseUrl,
                HANDLE_UNTRUSTED_CALLBACK,
                new ApiInfo.Api(ApiInfo.ApiName.GTS_API, 1),
                null,/*optionalServerForDebuggingInfo*/null);


        if (res == null) {
            LOG.error("No GTS connection can be created for auth");
        }
        return (HttpConnection) res;
    }

    public boolean hasValidConfig() {
        return baseUrl != null;
    }
}
