package be.iminds.ilabt.jfed.lowlevel.ssh_key_info;

import be.iminds.ilabt.jfed.lowlevel.GeniUser;
import be.iminds.ilabt.jfed.util.KeyUtil;

import javax.annotation.Nonnull;
import java.security.KeyPair;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.interfaces.RSAPrivateKey;

/**
 * User: twalcari
 * Date: 10/11/2016
 * Time: 10:31
 */
public class SshKeyInfoFactory {
    private SshKeyInfoFactory(){}

    public static BasicSshKeyInfo createBasicSshKeyInfo(PublicKey publicKey, PrivateKey privateKey) throws InvalidSshKeyInfoException {
        if (publicKey == null || privateKey == null)
            throw new InvalidSshKeyInfoException("Both public key and private key may not be null");
        return new BasicSshKeyInfo(publicKey, privateKey);
    }

    public static BasicSshKeyInfo createBasicSshKeyInfo(KeyPair keyPair) throws InvalidSshKeyInfoException {
        if (keyPair == null || keyPair.getPrivate() == null || keyPair.getPublic() == null)
            throw new InvalidSshKeyInfoException("Both public key and private key may not be null");
        return new BasicSshKeyInfo(keyPair);

    }

    public static BasicSshKeyInfo createBasicSshKeyInfoFromPrivateKeyOnly(PrivateKey privateKey) throws InvalidSshKeyInfoException {
        if (privateKey instanceof RSAPrivateKey) {
            PublicKey pubKey = KeyUtil.rsaPrivateKeyToRsaPublicKey((RSAPrivateKey) privateKey);

            if (pubKey == null)
                throw new InvalidSshKeyInfoException("Could not extract public key from the provided private key");

            return createBasicSshKeyInfo(pubKey, privateKey);
        } else
            throw new InvalidSshKeyInfoException(
                    "Could not extract public key from the provided private key (type: "
                            + (privateKey != null ? privateKey.getClass().getSimpleName() : "null") + ")");
    }

    public static GeniUserSshKeyInfo createGeniUserSshKeyInfo(@Nonnull GeniUser geniUser) {
        return new GeniUserSshKeyInfo(geniUser);
    }
}
