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

import com.jscape.inet.proxy.socks.protocol.v4.messages.ConnectRequest;
import com.jscape.inet.proxy.socks.protocol.v4.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.Inet4Address;
import java.nio.charset.StandardCharsets;

/**
 * @author Alex Usun
 */
public class ConnectRequestCodec
        implements DataCodec<Message> {

    @Override
    public Message read(InputStream in)
            throws IOException {
        int port = ShortCodec.readBigEndianValue(in) & 0xFFFF;
        Inet4Address ip = InetAddressCodec.readValue(in);
        String userId = StringCodec.readValue(StandardCharsets.US_ASCII, in);

        return new ConnectRequest(port, ip, userId);
    }

    @Override
    public void write(Message value, OutputStream out)
            throws IOException {
        ConnectRequest message = (ConnectRequest) value;
        ShortCodec.writeBigEndianValue((short) message.port, out);
        InetAddressCodec.writeValue(message.ip, out);
        StringCodec.writeValue(message.userId, StandardCharsets.US_ASCII, out);
    }
}
