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

import com.jscape.inet.ssh.protocol.messages.Message;
import com.jscape.inet.ssh.protocol.v2.marshaling.primitive.MpintCodec;
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.SshMsgKexDhReply;
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.math.BigInteger;
import java.security.PublicKey;

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

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

    private final DataCodec<PublicKey> publicKeyCodec;
    private final DataCodec<Signature> signatureCodec;

    public SshMsgKexDhReplyCodec(DataCodec<PublicKey> publicKeyCodec, DataCodec<Signature> signatureCodec) {
        assertNotNull(publicKeyCodec);
        this.publicKeyCodec = publicKeyCodec;

        assertNotNull(signatureCodec);
        this.signatureCodec = signatureCodec;
    }

    @Override
    public Message read(InputStream in)
            throws IOException {
        byte[] hostKeyData = StringCodec.readValue(in);
        PublicKey hostKey = this.publicKeyCodec.read(new ByteArrayInputStream(hostKeyData));
        BigInteger f = MpintCodec.readValue(in);
        Signature signature = this.signatureCodec.read(in);

        SshMsgKexDhReply message = new SshMsgKexDhReply(hostKey, f, signature);
        message.hostKeyBlob = hostKeyData;

        return message;
    }

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

        ByteArrayOutputStream buffer = new ByteArrayOutputStream();

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

        MpintCodec.writeValue(message.f, out);
        this.signatureCodec.write(message.signature, out);
    }
}
