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

import com.atlassian.bitbucket.i18n.I18nService;
import com.atlassian.bitbucket.repository.Repository;
import com.atlassian.bitbucket.scm.CommandExitHandler;
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.diff.GitDiffOutput;
import com.atlassian.bitbucket.scm.git.command.log.GitLogBuilder;
import com.atlassian.stash.internal.scm.git.command.revlist.AbstractGitRevCoreBuilder;

import javax.annotation.Nonnull;

import static java.util.Objects.requireNonNull;

/**
 * @since 4.5
 */
public class DefaultGitLogBuilder extends AbstractGitRevCoreBuilder<GitLogBuilder> implements GitLogBuilder {

    private final I18nService i18nService;
    private final Repository repository;

    private boolean follow;
    private GitDiffOutput output;
    private boolean useDefaultExitHandler;

    public DefaultGitLogBuilder(GitScmCommandBuilder builder, I18nService i18nService, Repository repository) {
        super(builder.command("log"));

        this.i18nService = i18nService;
        this.repository = repository;

        output = GitDiffOutput.DEFAULT;
        useDefaultExitHandler = true;
    }

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

        return super.build(outputHandler);
    }

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

        return self();
    }

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

        useDefaultExitHandler = false;

        return self();
    }

    @Nonnull
    @Override
    public GitLogBuilder follow(boolean value) {
        follow = value;

        return self();
    }

    @Nonnull
    @Override
    public GitLogBuilder output(@Nonnull GitDiffOutput value) {
        output = requireNonNull(value, "output");

        return self();
    }

    @Override
    protected void applyFlags() {
        super.applyFlags();

        if (follow) {
            builder.argument("--follow");
        }
        if (output.isFlagged()) {
            builder.argument(output.getFlag());
        }
    }

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