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

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

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

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

    private static final int RESERVED_FIELD_VALUE = 0;

    @Override
    public Message read(InputStream in)
            throws IOException {
        int version = ByteCodec.readValue(in) & 0xFF;
        assertVersionSupported(version);
        int status = ByteCodec.readValue(in) & 0xFF;
        int reserved = ByteCodec.readValue(in) & 0xFF;
        InetAddress boundAddress = InetAddressCodec.readValue(in);
        int boundPort = ShortCodec.readBigEndianValue(in) & 0xFFFF;

        return new CommandResponse(status, boundAddress, boundPort);
    }

    @Override
    public void write(Message value, OutputStream out)
            throws IOException {
        CommandResponse message = (CommandResponse) value;
        ByteCodec.writeValue((byte) VERSION, out);
        ByteCodec.writeValue((byte) message.status, out);
        ByteCodec.writeValue((byte) RESERVED_FIELD_VALUE, out);
        InetAddressCodec.writeValue(message.boundAddress, out);
        ShortCodec.writeBigEndianValue((short) message.boundPort, out);
    }

}
