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

import be.iminds.ilabt.jfed.util.KeyUtil;
import be.iminds.ilabt.jfed.util.tmp_file_helpers.TmpContentFile;
import be.iminds.ilabt.jfed.util.tmp_file_helpers.TmpFile;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.security.KeyPair;
import java.security.PrivateKey;
import java.security.PublicKey;

/**
 * BasicSshKeyInfo: SshKeyInfo with keys given in constructor
 * <p/>
 * typically just used to get keys, not typically used for files.
 * <p/>
 * does not support PuTTY
 */
public class BasicSshKeyInfo implements SshFilesKeyInfo{
    private final PublicKey sshPublicKey;
    private final PrivateKey sshPrivateKey;

    BasicSshKeyInfo(@Nonnull PublicKey sshPublicKey, @Nonnull PrivateKey sshPrivateKey) {
        this.sshPublicKey = sshPublicKey;
        this.sshPrivateKey = sshPrivateKey;
    }
    BasicSshKeyInfo(@Nonnull KeyPair keyPair) {
        this.sshPublicKey = keyPair.getPublic();
        this.sshPrivateKey = keyPair.getPrivate();
    }

    @Override
    public TmpFile getPrivateKeyFile() {
        return getUnencryptedPrivateKeyFile();
    }

    @Override
    public TmpFile getUnencryptedPrivateKeyFile() {
        String pemKey = new String(KeyUtil.privateKeyToAnyPem(sshPrivateKey));
        return new TmpContentFile("sskKeyBasUE", "pem", pemKey, true/*assureUserOnlyPermissions*/);
    }

    @Override
    public boolean hasUnencryptedPrivateKey() {
        return sshPrivateKey != null;
    }

    @Override
    public boolean isLocked() {
        return false;
    }

    @Override
    public boolean unlock(char[] password) {
        throw new IllegalStateException("BasicSshKeyInfo does not supported locked private keys");
    }


    @Nonnull
    @Override
    public PublicKey getPublicKey() {
        return sshPublicKey;
    }

    @Override
    public PrivateKey getPrivateKey() {
        return sshPrivateKey;
    }

    @Nullable
    @Override
    public String getComment() {
        return null;
    }
}
