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

import com.atlassian.bitbucket.i18n.I18nService;
import com.atlassian.bitbucket.repository.Repository;
import com.atlassian.bitbucket.scm.CommandExitHandler;
import com.atlassian.bitbucket.scm.CommandInputHandler;
import com.atlassian.bitbucket.scm.CommandOutputHandler;
import com.atlassian.bitbucket.scm.git.command.GitCommand;
import com.atlassian.bitbucket.scm.git.command.GitScmCommandBuilder;
import com.atlassian.bitbucket.scm.git.command.catfile.GitCatFileBatchBuilder;
import com.atlassian.stash.internal.scm.git.command.AbstractGitCommandBuilder;

import javax.annotation.Nonnull;

import static java.util.Objects.requireNonNull;

public class DefaultGitCatFileBatchBuilder extends AbstractGitCommandBuilder<GitCatFileBatchBuilder> implements GitCatFileBatchBuilder {

    private final CatFileFormat format;
    private final CommandInputHandler inputHandler;
    private final I18nService i18nService;
    private final Repository repository;

    private boolean useDefaultExitHandler;

    protected DefaultGitCatFileBatchBuilder(GitScmCommandBuilder builder, I18nService i18nService, Repository repository,
                                            CatFileFormat format, CommandInputHandler inputHandler) {
        super(builder);
        this.format = requireNonNull(format, "format");
        this.inputHandler = requireNonNull(inputHandler, "inputHandler");
        this.i18nService = i18nService;
        this.repository = repository;

        useDefaultExitHandler = true;
    }

    @Nonnull
    @Override
    public <T> GitCommand<T> build(@Nonnull CommandOutputHandler<T> outputHandler) {
        if (useDefaultExitHandler) {
            builder.exitHandler(new CatFileBatchCommandExitHandler(i18nService, repository));
        }
        return super.build(outputHandler);
    }

    @Nonnull
    @Override
    public GitCatFileBatchBuilder defaultExitHandler() {
        useDefaultExitHandler = true;

        return self();
    }

    @Nonnull
    @Override
    public GitCatFileBatchBuilder exitHandler(@Nonnull CommandExitHandler value) {
        super.exitHandler(value);

        useDefaultExitHandler = false;

        return self();
    }

    @Override
    protected void applyArguments() {
        builder.inputHandler(inputHandler);
        builder.argument(format.getFlag());
    }

    @Nonnull
    @Override
    protected GitCatFileBatchBuilder self() {
        return this;
    }
}
