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

import be.iminds.ilabt.jfed.lowlevel.ssh_key_info.PuTTYFilesKeyInfo;
import be.iminds.ilabt.jfed.lowlevel.ssh_key_info.SshFilesKeyInfo;
import be.iminds.ilabt.jfed.lowlevel.ssh_key_info.putty.PuTTYPrivateKeyFile;
import be.iminds.ilabt.jfed.util.tmp_file_helpers.PermanentFile;
import be.iminds.ilabt.jfed.util.tmp_file_helpers.TmpFile;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.io.File;
import java.security.PrivateKey;
import java.security.PublicKey;

/**
 * PreferencesSshKeyInfo
 * <p/>
 * this normally never needs the private key, so it doesn't return it
 */
public class PreferencesPuttySshKeyInfo implements PuTTYFilesKeyInfo, SshFilesKeyInfo {
    @Nonnull
    private final File ppkFile;
    @Nonnull
    private final PuTTYPrivateKeyFile ppk;

    @Nonnull
    private final PublicKey publicKey;
    private PrivateKey privateKey;


    PreferencesPuttySshKeyInfo(@Nonnull File ppkFile, @Nonnull PuTTYPrivateKeyFile ppk) {
        this.ppkFile = ppkFile;
        this.ppk = ppk;
        this.publicKey = ppk.getPublicKey();

        if (!ppk.isEncrypted())
            this.privateKey = ppk.getPrivateKey();
        else
            this.privateKey = null;


    }

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

    @Override
    public TmpFile getPuttyKeyFile() {
        return new PermanentFile(ppkFile);
    }

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

    @Override
    public TmpFile getUnlockedPuttyKeyFile() {
        return null;
    }

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

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

    @Override
    public boolean isLocked() {
        return ppk.isEncrypted();
    }

    @Override
    public boolean unlock(char[] password) {
        if (ppk.unlock(new String(password))) {
            this.privateKey = ppk.getPrivateKey();

            return true;
        } else return false;

    }

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

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

    public PuTTYPrivateKeyFile getPPK() {
        return ppk;
    }
}
