package com.jscape.inet.ssh.protocol.v2.marshaling;

import com.jscape.inet.ssh.protocol.v2.marshaling.primitive.StringCodec;
import com.jscape.inet.ssh.protocol.v2.messages.SshMsgUserAuthRequest;
import com.jscape.inet.ssh.protocol.v2.messages.SshMsgUserAuthRequestNewPassword;
import com.jscape.inet.ssh.protocol.v2.messages.SshMsgUserAuthRequestPassword;
import com.jscape.util.io.primitive.BooleanCodec;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * @author Alex Usun
 */
public class SshMsgUserAuthRequestPasswordCodec
        implements SshMsgUserAuthRequestCodec.MethodCodec {

    @Override
    public SshMsgUserAuthRequest read(InputStream in, String username, String serviceName)
            throws IOException {
        boolean newPasswordRequest = BooleanCodec.readValue(in);

        if (newPasswordRequest) {
            String oldPassword = StringCodec.readUtf8Value(in);
            String newPassword = StringCodec.readUtf8Value(in);

            return new SshMsgUserAuthRequestNewPassword(username, serviceName, oldPassword, newPassword);
        } else {
            String password = StringCodec.readUtf8Value(in);

            return new SshMsgUserAuthRequestPassword(username, serviceName, password);
        }
    }

    @Override
    public void write(SshMsgUserAuthRequest value, OutputStream out)
            throws IOException {
        if (value instanceof SshMsgUserAuthRequestNewPassword) {
            SshMsgUserAuthRequestNewPassword message = (SshMsgUserAuthRequestNewPassword) value;
            BooleanCodec.writeValue(true, out);
            StringCodec.writeUtf8Value(message.oldPassword, out);
            StringCodec.writeUtf8Value(message.newPassword, out);
        } else {
            SshMsgUserAuthRequestPassword message = (SshMsgUserAuthRequestPassword) value;
            BooleanCodec.writeValue(false, out);
            StringCodec.writeUtf8Value(message.password, out);
        }
    }
}
