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

import com.atlassian.bitbucket.ssh.command.SshCommand;
import com.atlassian.bitbucket.ssh.command.SshCommandFactory;
import com.atlassian.bitbucket.ssh.command.SshCommandFactoryModuleDescriptor;
import com.atlassian.plugin.PluginAccessor;

import javax.annotation.Nonnull;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Optional;
import java.util.stream.Stream;

import static com.atlassian.bitbucket.util.ModuleDescriptorUtils.toSortedModules;

public class PluginSshCommandProvider implements SshCommandProvider {

    private final PluginAccessor pluginAccessor;

    public PluginSshCommandProvider(PluginAccessor pluginAccessor) {
        this.pluginAccessor = pluginAccessor;
    }

    @Nonnull
    @Override
    public Optional<SshCommand> getSshCommand(@Nonnull String command, @Nonnull InputStream in,
                                              @Nonnull OutputStream out, @Nonnull OutputStream err) {
        return getHandlers()
                .filter(handler -> handler.supports(command))
                .findFirst()
                .flatMap(handler -> handler.create(command, in, out, err));
    }

    private Stream<SshCommandFactory> getHandlers() {
        return toSortedModules(pluginAccessor.getEnabledModuleDescriptorsByClass(SshCommandFactoryModuleDescriptor.class));
    }
}
