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

import com.jscape.inet.ssh.protocol.v2.marshaling.MessageCodec;
import com.jscape.inet.ssh.protocol.v2.messages.UserAuthInfoRequestPrompt;
import com.jscape.util.cli.Console;

import java.util.ArrayList;
import java.util.List;

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

/**
 * Represents a SSH 'keyboard-interactive' authentication operation which uses a console for obtaining required authentication information.
 *
 * @author Alex Usun
 */
public class KeyboardInteractiveConsoleClientAuthentication
        extends AbstractKeyboardInteractiveClientAuthentication {

    private final Console console;

    /**
     * Returns an authentication operation which uses a system console.
     *
     * @param username an username
     *
     * @return an authentication operation instance
     */
    public static KeyboardInteractiveConsoleClientAuthentication systemConsoleAuthentication(MessageCodec.Factory codecFactory, String username) {
        return new KeyboardInteractiveConsoleClientAuthentication(codecFactory, username, Console.systemConsole());
    }

    /**
     * Returns an authentication operation which uses a system console.
     *
     * @param username an username
     *
     * @return an authentication operation instance
     */
    public static KeyboardInteractiveConsoleClientAuthentication systemConsoleAuthentication(String username) {
        return new KeyboardInteractiveConsoleClientAuthentication(KeyboardInteractiveMessages.defaultMessages(), username, Console.systemConsole());
    }

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

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

    @Override
    protected List<String> responsesFor(String name, String instruction, List<UserAuthInfoRequestPrompt> prompts)
            throws Exception {
        this.console.println(name);
        this.console.println(instruction);

        List<String> responses = new ArrayList<>(prompts.size());
        for (UserAuthInfoRequestPrompt prompt : prompts) {
            String response = this.console.prompt(prompt.prompt);
            responses.add(response);
        }

        return responses;
    }
}
