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

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

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;

/**
 * @author Alex Usun
 */
public class PasswordAuthenticationRequestCodec
        extends BaseAuthenticationCodec {

    @Override
    public Message read(InputStream in)
            throws IOException {
        int version = ByteCodec.readValue(in) & 0xFF;
        assertVersionSupported(version);
        String username = ByteStringCodec.readValue(StandardCharsets.UTF_8, in);
        String password = ByteStringCodec.readValue(StandardCharsets.UTF_8, in);

        return new PasswordAuthenticationRequest(username, password);
    }

    @Override
    public void write(Message value, OutputStream out)
            throws IOException {
        PasswordAuthenticationRequest message = (PasswordAuthenticationRequest) value;
        ByteCodec.writeValue((byte) VERSION, out);
        ByteStringCodec.writeValue(message.username, StandardCharsets.UTF_8, out);
        ByteStringCodec.writeValue(message.password, StandardCharsets.UTF_8, out);
    }

}
