package com.jscape.inet.ssh.protocol.v2.marshaling;

import com.jscape.inet.ssh.protocol.messages.Message;
import com.jscape.inet.ssh.protocol.v2.marshaling.keys.EcPublicKeyCodec;
import com.jscape.inet.ssh.protocol.v2.marshaling.primitive.StringCodec;
import com.jscape.inet.ssh.protocol.v2.messages.Signature;
import com.jscape.inet.ssh.protocol.v2.messages.SshMsgKexEcdhReply;
import com.jscape.util.io.ByteArrayInputStream;
import com.jscape.util.io.ByteArrayOutputStream;
import com.jscape.util.io.DataCodec;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.PublicKey;

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

/**
 * @author Alex Usun
 */
public class SshMsgKexEcdhReplyCodec
        implements DataCodec<Message> {

    private final DataCodec<PublicKey> publicKeyCodec;
    private final DataCodec<Signature> signatureCodec;
    private final String curveIdentifier;
    private final Object provider;

    public SshMsgKexEcdhReplyCodec(DataCodec<PublicKey> publicKeyCodec, DataCodec<Signature> signatureCodec, String curveIdentifier, Object provider) {
        assertNotNull(publicKeyCodec);
        this.publicKeyCodec = publicKeyCodec;

        assertNotNull(signatureCodec);
        this.signatureCodec = signatureCodec;

        assertNotNull(curveIdentifier);
        this.curveIdentifier = curveIdentifier;

        this.provider = provider;
    }

    @Override
    public Message read(InputStream in)
            throws IOException {
        byte[] hostKeyData = StringCodec.readValue(in);
        PublicKey hostKey = this.publicKeyCodec.read(new ByteArrayInputStream(hostKeyData));
        PublicKey qs = EcPublicKeyCodec.readValue(this.curveIdentifier, this.provider, in);
        Signature signature = this.signatureCodec.read(in);

        SshMsgKexEcdhReply message = new SshMsgKexEcdhReply(hostKey, qs, signature);
        message.hostKeyBlob = hostKeyData;

        return message;
    }

    @Override
    public void write(Message value, OutputStream out)
            throws IOException {
        SshMsgKexEcdhReply message = (SshMsgKexEcdhReply) value;

        ByteArrayOutputStream buffer = new ByteArrayOutputStream();

        this.publicKeyCodec.write(message.hostKey, buffer);
        StringCodec.writeValue(buffer.buffer(), 0, buffer.position(), out);
        message.hostKeyBlob = buffer.toByteArray();

        EcPublicKeyCodec.writeValue(message.qs, out);
        this.signatureCodec.write(message.signature, out);
    }
}
