package com.jscape.inet.ssh.protocol.v2.transport.keyexchange;

import com.jscape.inet.ssh.protocol.v2.marshaling.MessageCodec;
import com.jscape.inet.ssh.protocol.v2.marshaling.SshMsgKexDhInitCodec;
import com.jscape.inet.ssh.protocol.v2.marshaling.SshMsgKexDhReplyCodec;
import com.jscape.inet.ssh.protocol.v2.marshaling.keys.PublicKeyCodec;
import com.jscape.inet.ssh.protocol.v2.marshaling.keys.PublicKeyCodecs;
import com.jscape.inet.ssh.protocol.v2.marshaling.keys.SignatureCodec;
import com.jscape.inet.ssh.protocol.v2.marshaling.keys.SignatureCodecs;
import com.jscape.inet.ssh.protocol.v2.messages.Signature;
import com.jscape.inet.ssh.protocol.v2.messages.SshMsgKexDhInit;
import com.jscape.inet.ssh.protocol.v2.messages.SshMsgKexDhReply;
import com.jscape.util.crypto.CryptoServicesProvider;
import com.jscape.util.io.DataCodec;

import java.security.Provider;
import java.security.PublicKey;

import static com.jscape.util.Parameters.assertNotNull;

/**
 * @author Alex Usun
 */
public class DiffieHellmanKeyExchangeMessages
        implements MessageCodec.Factory {

    private final MessageCodec.Entry[] entries;

    public static DiffieHellmanKeyExchangeMessages defaultMessages() {
        return defaultMessages(CryptoServicesProvider.instance());
    }

    public static DiffieHellmanKeyExchangeMessages defaultMessages(String provider) {
        DataCodec<PublicKey> publicKeyCodec = PublicKeyCodecs.init(new PublicKeyCodec(), provider);
        DataCodec<Signature> signatureCodec = SignatureCodecs.init(new SignatureCodec());

        return new DiffieHellmanKeyExchangeMessages(new MessageCodec.Entry(30, new SshMsgKexDhInitCodec(), SshMsgKexDhInit.class),
                                                    new MessageCodec.Entry(31, new SshMsgKexDhReplyCodec(publicKeyCodec, signatureCodec), SshMsgKexDhReply.class));
    }

    public static DiffieHellmanKeyExchangeMessages defaultMessages(Provider provider) {
        DataCodec<PublicKey> publicKeyCodec = PublicKeyCodecs.init(new PublicKeyCodec(), provider);
        DataCodec<Signature> signatureCodec = SignatureCodecs.init(new SignatureCodec());

        return new DiffieHellmanKeyExchangeMessages(new MessageCodec.Entry(30, new SshMsgKexDhInitCodec(), SshMsgKexDhInit.class),
                                                    new MessageCodec.Entry(31, new SshMsgKexDhReplyCodec(publicKeyCodec, signatureCodec), SshMsgKexDhReply.class));
    }

    public DiffieHellmanKeyExchangeMessages(MessageCodec.Entry... entries) {
        assertNotNull(entries);
        this.entries = entries;
    }

    @Override
    public MessageCodec update(MessageCodec codec) {
        return codec.set(this.entries);
    }
}
