package com.atlassian.bitbucket.internal.ssh.who;

import com.atlassian.bitbucket.auth.AuthenticationContext;
import com.atlassian.bitbucket.ssh.command.SshCommand;
import com.atlassian.bitbucket.user.ApplicationUser;

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

/**
 * A simple command which echos the current user's name to an output stream.
 */
public class WhoAmISshCommand implements SshCommand {

    private final AuthenticationContext authenticationContext;
    private final OutputStream stdout;

    public WhoAmISshCommand(AuthenticationContext authenticationContext, OutputStream stdout) {
        this.authenticationContext = authenticationContext;
        this.stdout = stdout;
    }

    @Override
    public void cancel() {
        //No-op. This command completes quickly enough it's unlikely it could ever be canceled
    }

    /**
     * Echoes the {@link AuthenticationContext#getCurrentUser() current user} to the
     * {@code OutputStream} provided during construction. If there is no context user, "&lt;anonymous&gt;" is echoed
     * instead.
     *
     * @throws IOException thrown if the username cannot be written to the stream
     */
    @Override
    public int run() throws IOException {
        ApplicationUser user = authenticationContext.getCurrentUser();
        String who = user == null ? "<anonymous>" : user.getName();

        stdout.write(who.getBytes());
        stdout.write('\n');
        stdout.flush();

        return 0;
    }
}
