package com.atlassian.stash.internal.scm.git;

import com.atlassian.bitbucket.i18n.I18nService;
import com.atlassian.bitbucket.repository.Repository;
import com.atlassian.bitbucket.scm.git.command.GitCommandBuilderFactory;
import com.atlassian.bitbucket.scm.git.command.GitScmCommandBuilder;
import com.google.common.collect.ImmutableList;

import javax.annotation.Nonnull;
import java.util.List;

/**
 * @since 1.3
 */
public class DefaultGitCommandBuilderFactory implements GitCommandBuilderFactory {

    private final InternalGitScmConfig config;
    private final List<GitCommandBuilderConfigurer> configurers;
    private final I18nService i18nService;

    public DefaultGitCommandBuilderFactory(InternalGitScmConfig config, List<GitCommandBuilderConfigurer> configurers,
                                           I18nService i18nService) {
        this.config = config;
        this.configurers = ImmutableList.copyOf(configurers);
        this.i18nService = i18nService;
    }

    @Nonnull
    @Override
    public GitScmCommandBuilder builder() {
        return builder(null);
    }

    @Nonnull
    @Override
    public GitScmCommandBuilder builder(Repository repository) {
        return configure(new DefaultGitScmCommandBuilder(i18nService, config, repository));
    }

    /**
     * Applies the injected set of {@link GitCommandBuilderConfigurer GitCommandBuilderConfigurers} to the provided
     * {@link GitScmCommandBuilder builder} and then returns it.
     *
     * @param builder the {@link GitScmCommandBuilder builder} to configure
     * @return the provided {@code builder}
     * @since 3.1
     */
    private GitScmCommandBuilder configure(GitScmCommandBuilder builder) {
        for (GitCommandBuilderConfigurer configurer : configurers) {
            configurer.configure(builder);
        }

        return builder;
    }
}
