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

import com.jscape.inet.proxy.socks.protocol.v5.messages.AssociateUdpRequest;
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 AssociateUdpRequestCodec
        implements DataCodec<Message> {

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

        return new AssociateUdpRequest(destinationAddress, port);
    }

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