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

import com.jscape.inet.proxy.socks.protocol.v5.messages.BindRequest;
import com.jscape.inet.proxy.socks.protocol.v5.messages.Message;
import com.jscape.util.io.DataCodec;
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 BindRequestCodec
        implements DataCodec<Message> {

    @Override
    public Message read(InputStream in)
            throws IOException {
        InetAddress destinationAddress = InetAddressCodec.readValue(in);
        int port = ShortCodec.readBigEndianValue(in) & 0xFFFF;

        return new BindRequest(destinationAddress, port);
    }

    @Override
    public void write(Message value, OutputStream out)
            throws IOException {
        BindRequest message = (BindRequest) value;
        InetAddressCodec.writeValue(message.destinationAddress, out);
        ShortCodec.writeBigEndianValue((short) message.port, out);
    }
}
