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

import com.jscape.inet.proxy.socks.protocol.v4.messages.CommandResponse;
import com.jscape.inet.proxy.socks.protocol.v4.messages.Message;
import com.jscape.util.io.DataCodec;
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.Inet4Address;

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

    private static final int VERSION = 0;

    @Override
    public Message read(InputStream in)
            throws IOException {
        int version = ByteCodec.readValue(in) & 0xFF;
        assertVersionSupported(version);
        int result = ByteCodec.readValue(in) & 0xFF;
        int port = ShortCodec.readBigEndianValue(in) & 0xFFFF;
        Inet4Address ip = InetAddressCodec.readValue(in);

        return new CommandResponse(result, port, ip);
    }

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

    private void assertVersionSupported(int version)
            throws IOException {
        if (version != VERSION) {
            throw new IOException("Unsupported message version: " + version);
        }
    }

}
