package be.iminds.ilabt.jfed.preferences;

import be.iminds.ilabt.jfed.highlevel.model.SfaModel;
import be.iminds.ilabt.jfed.lowlevel.GeniUser;
import be.iminds.ilabt.jfed.lowlevel.GeniUserProvider;
import be.iminds.ilabt.jfed.lowlevel.ssh_key_info.SshKeyInfo;
import be.iminds.ilabt.jfed.lowlevel.ssh_key_info.SshKeyInfoFactory;
import be.iminds.ilabt.jfed.util.KeyUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.inject.Inject;
import javax.inject.Singleton;

/**
 * User: twalcari
 * Date: 2/3/2015
 * Time: 16:26
 */
@Singleton
public class JFedPreferencesApplierImpl implements JFedPreferencesApplier {
    private static final Logger LOG = LoggerFactory.getLogger(JFedPreferencesApplierImpl.class);

    private final JFedGuiPreferences jFedPreferences;
    private final SfaModel sfaModel;
    private final GeniUserProvider geniUserProvider;
    private final ProxyPreferencesManager proxyPreferencesManager;

    @Inject
    public JFedPreferencesApplierImpl(JFedGuiPreferences jFedPreferences, SfaModel sfaModel, GeniUserProvider geniUserProvider, ProxyPreferencesManager proxyPreferencesManager) {
        this.jFedPreferences = jFedPreferences;
        this.sfaModel = sfaModel;
        this.geniUserProvider = geniUserProvider;
        this.proxyPreferencesManager = proxyPreferencesManager;
    }

    @Override
    public void applyPreferences() {
        registerPrivateKeys();
        proxyPreferencesManager.updateProxySettings();
    }

    private void registerPrivateKeys() {
        //set user key to key in login cert (always do this: used for jFed internal SSH connections, see https://ibcn-jira.intec.ugent.be/browse/FEDIBBTDEV-406),
        // also add key from configuration if present.
        final GeniUser geniUser = geniUserProvider.getLoggedInGeniUser();
        SshKeyInfo userSshKeyInfo = SshKeyInfoFactory.createGeniUserSshKeyInfo(geniUser);
        SshKeyInfo customSshKeyInfo = jFedPreferences.getCustomSshKeyInfo();
        if (customSshKeyInfo != null) {
            String customPubKeyStr =
                    KeyUtil.publicKeyToOpenSshAuthorizedKeysFormat(customSshKeyInfo.getPublicKey());
            LOG.info("Will add public key from configuration to created slivers: " + customPubKeyStr);
            sfaModel.addUserKey(customPubKeyStr);
        }

        if (userSshKeyInfo.getPublicKey() != null) {
            String userPubKeyStr = KeyUtil.publicKeyToOpenSshAuthorizedKeysFormat(userSshKeyInfo.getPublicKey());
            LOG.info("Will add user specified public key to created slivers: " + userPubKeyStr);
            sfaModel.addUserKey(userPubKeyStr);
        } else
            LOG.warn("No public key in userSshKeyInfo (class=" + userSshKeyInfo.getClass().getName() + ")");


    }

}
