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

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

import javax.annotation.Nonnull;

import static java.util.Objects.requireNonNull;

public class DefaultGitMergeTreeBuilder
        extends AbstractGitProcessBuilder<GitMergeTreeBuilder>
        implements GitMergeTreeBuilder {

    private boolean allowUnrelatedHistories;
    private String branch1;
    private String branch2;
    private boolean messages;
    private boolean nameOnly;
    private boolean nullTerminated;

    public DefaultGitMergeTreeBuilder(GitProcessBuilder builder) {
        super(builder.command("merge-tree"));
    }

    @Nonnull
    @Override
    public GitMergeTreeBuilder allowUnrelatedHistories(boolean value) {
        allowUnrelatedHistories = value;
        return self();
    }

    @Nonnull
    @Override
    public GitMergeTreeBuilder branch1(@Nonnull String value) {
        branch1 = requireNonNull(value, "branch1");
        return self();
    }

    @Nonnull
    @Override
    public GitMergeTreeBuilder branch2(@Nonnull String value) {
        branch2 = requireNonNull(value, "branch2");
        return self();
    }

    @Nonnull
    @Override
    public GitMergeTreeBuilder messages(boolean value) {
        messages = value;
        return self();
    }

    @Nonnull
    @Override
    public GitMergeTreeBuilder nameOnly(boolean value) {
        nameOnly = value;
        return self();
    }

    @Nonnull
    @Override
    public GitMergeTreeBuilder nullTerminated(boolean value) {
        nullTerminated = value;
        return self();
    }

    @Override
    protected void applyArguments() {
        builder.argument("--write-tree");
        if (allowUnrelatedHistories) {
            builder.argument("--allow-unrelated-histories");
        }
        if (messages) {
            builder.argument("--messages");
        } else {
            builder.argument("--no-messages");
        }
        if (nameOnly) {
            builder.argument("--name-only");
        }
        if (nullTerminated) {
            builder.argument("-z");
        }
        builder.commitish(branch1);
        builder.commitish(branch2);
    }

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