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.StringCodec;
import com.jscape.inet.ssh.protocol.v2.messages.SshMsgUserAuthPkOk;
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 SshMsgUserAuthPkOkCodec
        implements DataCodec<Message> {

    private final DataCodec<PublicKey> publicKeyCodec;

    public SshMsgUserAuthPkOkCodec(DataCodec<PublicKey> publicKeyCodec) {
        assertNotNull(publicKeyCodec);
        this.publicKeyCodec = publicKeyCodec;
    }

    @Override
    public Message read(InputStream in)
            throws IOException {
        String publicKeyAlgorithm = StringCodec.readUsAsciiValue(in);
        byte[] publicKeyData = StringCodec.readValue(in);
        PublicKey publicKey = this.publicKeyCodec.read(new ByteArrayInputStream(publicKeyData));

        return new SshMsgUserAuthPkOk(publicKeyAlgorithm, publicKey);
    }

    @Override
    public void write(Message value, OutputStream out)
            throws IOException {
        SshMsgUserAuthPkOk message = (SshMsgUserAuthPkOk) value;
        StringCodec.writeUsAsciiValue(message.publicKeyAlgorithm, out);

        ByteArrayOutputStream buffer = new ByteArrayOutputStream();
        this.publicKeyCodec.write(message.publicKey, buffer);
        StringCodec.writeValue(buffer.buffer(), 0, buffer.position(), out);
    }
}
