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

import com.jscape.inet.ssh.protocol.messages.Message;
import com.jscape.inet.ssh.protocol.v2.marshaling.MessageCodec;
import com.jscape.inet.ssh.protocol.v2.messages.SshMsgUserAuthRequestNone;
import com.jscape.inet.ssh.protocol.v2.transport.TransportConnection;

import static com.jscape.util.Parameters.assertNotNull;

/**
 * Represents a SSH 'none' authentication operation.
 *
 * @author Alex Usun
 */
public class NoneClientAuthentication
        extends AbstractClientAuthentication {

    private final String username;

    public static NoneClientAuthentication defaultAuthentication(String username) {
        return new NoneClientAuthentication(PasswordAuthenticationMessages.defaultMessages(), username);
    }

    /**
     * Creates a new operation instance.
     *
     * @param username an username
     */
    public NoneClientAuthentication(MessageCodec.Factory codecFactory, String username) {
        super(codecFactory);

        assertNotNull(username);
        this.username = username;
    }

    @Override
    public void applyTo(TransportConnection connection, String serviceName)
            throws Exception {
        init(connection);
        sendUsername(connection, serviceName);
    }

    @Override
    public String toString() {
        return "NoneClientAuthentication {"
               + "username='" + this.username + '\''
               + ", banner='" + this.banner + '\''
               + ", bannerLanguageTag='" + this.bannerLanguageTag + '\''
               + '}';
    }

    protected void init(TransportConnection connection) {
        super.init(connection);
        this.codecFactory.update(connection.session().messageCodec);
    }

    private void sendUsername(TransportConnection connection, String serviceName)
            throws Exception {
        connection.write(new SshMsgUserAuthRequestNone(this.username, serviceName));
        Message response = receive(connection);
        assertSuccess(response);
    }

}
