package com.atlassian.bitbucket.mesh.git.builder.revlist;

import com.atlassian.bitbucket.mesh.git.builder.GitProcessBuilder;

import javax.annotation.Nonnull;

public class DefaultGitRevListBuilder
        extends AbstractGitRevCoreBuilder<GitRevListBuilder>
        implements GitRevListBuilder {

    private boolean count;

    public DefaultGitRevListBuilder(GitProcessBuilder builder) {
        super(builder.command("rev-list"));

    }

    @Nonnull
    @Override
    public GitRevListBuilder count(boolean value) {
        count = value;

        return self();
    }

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

        if (count) {
            builder.argument("--count");
        }
    }

    @Override
    protected void applyRevs() {
        //This revs.isEmpty() check results in a git rev-list command that works more like git log, which automatically
        //uses HEAD if no explicit starting rev is specified. Ultimately this probably should not have been done this
        //way, though its goal (helping to prevent plugin developers from building invalid rev-list commands) was noble.
        //However, with this logic having been here since the builders were introduced in 1.1, it's unlikely to change.
        if (revs.isEmpty()) {
            //If no explicit revs were supplied, add "HEAD" to list the default branch. Note that if --all, --branches
            //or --tags is used, then revs _have_ been supplied. If --stdin is used, we can't know for sure if revs
            //will be supplied, but we have to assume they will be
            if (!(all || branches || stdin || tags)) {
                //HEAD implicitly resolves the default branch. That means we don't have to use the GitAgent to resolve
                //it so that we can pass it in--let git do the heavy lifting internally.
                //
                //Note: The trailing --, added below, tells git that we are trying to send in a commit ID. This way,
                //if something that would otherwise be ambiguous (maybe a path, maybe a commit ID) is provided, git
                //will know which it should be treated as.
                builder.argument("HEAD");
            }
        } else {
            revs.forEach(builder::commitish);
        }
    }

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