package com.jscape.inet.proxy.socks.protocol.v5.marshaling;

import com.jscape.inet.proxy.socks.protocol.v5.messages.AuthenticationMethodRequest;
import com.jscape.inet.proxy.socks.protocol.v5.messages.Message;
import com.jscape.util.io.primitive.ByteCodec;

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

/**
 * @author Alex Usun
 */
public class AuthenticationMethodRequestCodec
        extends BaseCodec {

    @Override
    public Message read(InputStream in)
            throws IOException {
        int version = ByteCodec.readValue(in) & 0xFF;
        assertVersionSupported(version);
        int length = ByteCodec.readValue(in) & 0xFF;
        int[] methods = new int[length];
        for (int i = 0; i < methods.length; ++i) {
            methods[i] = ByteCodec.readValue(in) & 0xFF;
        }

        return new AuthenticationMethodRequest(methods);
    }

    @Override
    public void write(Message value, OutputStream out)
            throws IOException {
        AuthenticationMethodRequest message = (AuthenticationMethodRequest) value;
        ByteCodec.writeValue((byte) VERSION, out);
        ByteCodec.writeValue((byte) message.methods.length, out);
        for (int i = 0; i < message.methods.length; ++i) {
            ByteCodec.writeValue((byte) message.methods[i], out);
        }
    }


}
