package be.iminds.ilabt.jfed.experiment;

import be.iminds.ilabt.jfed.highlevel.util.ProxySocketFactoryProvider;
import be.iminds.ilabt.jfed.lowlevel.GeniUserProvider;
import be.iminds.ilabt.jfed.preferences.ProxyPreferencesManager;
import be.iminds.ilabt.jfed.util.ProxyServiceUtil;

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

/**
 * User: twalcari
 * Date: 8/22/2016
 * Time: 17:50
 */
@Singleton
public class SshConnectionPoolFactory {

    //by using a WeakHashmap, we prevent memory leaks from old experiments
    private final Map<Experiment, SshConnectionPool> connectionPoolMap = new WeakHashMap<>();


    private final GeniUserProvider geniUserProvider;
    private final ProxySocketFactoryProvider proxySocketFactoryProvider;
    private final ProxyPreferencesManager proxyPreferencesManager;
    private final ProxyServiceUtil proxyServiceUtil;

    @Inject
    SshConnectionPoolFactory(GeniUserProvider geniUserProvider, ProxySocketFactoryProvider proxySocketFactoryProvider,
                             ProxyPreferencesManager proxyPreferencesManager, ProxyServiceUtil proxyServiceUtil) {
        this.geniUserProvider = geniUserProvider;
        this.proxySocketFactoryProvider = proxySocketFactoryProvider;
        this.proxyPreferencesManager = proxyPreferencesManager;
        this.proxyServiceUtil = proxyServiceUtil;
    }

    public SshConnectionPool getSshConnectionPool(Experiment experiment) {
        return connectionPoolMap.computeIfAbsent(experiment,
                exp ->
                        new SshConnectionPool(exp, geniUserProvider.getLoggedInGeniUser(), proxySocketFactoryProvider,
                                proxyPreferencesManager, proxyServiceUtil));
    }

}
