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

import com.atlassian.bitbucket.mesh.git.builder.AbstractGitProcessBuilder;
import com.atlassian.bitbucket.mesh.git.builder.GitProcessBuilder;
import org.apache.commons.lang3.StringUtils;

import javax.annotation.Nonnull;

import static java.util.Objects.requireNonNull;

public class DefaultGitFormatPatchBuilder
        extends AbstractGitProcessBuilder<GitFormatPatchBuilder>
        implements GitFormatPatchBuilder {

    private boolean allAncestors;
    private String ancestor;
    private String rev;

    public DefaultGitFormatPatchBuilder(GitProcessBuilder builder) {
        super(builder.command("format-patch"));
    }

    @Nonnull
    @Override
    public GitFormatPatchBuilder allAncestors(boolean value) {
        allAncestors = value;

        return self();
    }

    @Nonnull
    @Override
    public GitFormatPatchBuilder ancestor(String value) {
        ancestor = StringUtils.trimToNull(value);

        return self();
    }

    @Nonnull
    @Override
    public GitFormatPatchBuilder rev(@Nonnull String value) {
        rev = requireNonNull(value, "value");

        return self();
    }

    @Override
    protected void applyArguments() {
        builder.argument("--stdout");
        if (allAncestors) {
            builder.argument("--root");
        } else if (ancestor == null) {
            builder.argument("-1");
        } else {
            builder.argument("^" + ancestor);
        }
        builder.commitish(rev)
                .argument("--");
    }

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