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

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

import javax.annotation.Nonnull;

import static com.google.common.base.Preconditions.checkArgument;

public class DefaultGitBranchCreateBuilder
        extends AbstractGitProcessBuilder<GitBranchCreateBuilder>
        implements GitBranchCreateBuilder {

    private final String name;

    private boolean force;
    private boolean reflog;
    private String startPoint;
    private boolean track;

    public DefaultGitBranchCreateBuilder(GitProcessBuilder builder, String name) {
        super(builder);

        checkArgument(StringUtils.isNotBlank(name), "A branch name is required");
        this.name = name;
    }

    @Nonnull
    @Override
    public GitProcess<Void> build() {
        return buildWithLoggingHandler();
    }

    @Nonnull
    @Override
    public GitBranchCreateBuilder force(boolean value) {
        force = value;

        return self();
    }

    @Nonnull
    @Override
    public GitBranchCreateBuilder reflog(boolean value) {
        reflog = value;

        return self();
    }

    @Nonnull
    @Override
    public GitBranchCreateBuilder startPoint(String value) {
        startPoint = value;

        return self();
    }

    @Nonnull
    @Override
    public GitBranchCreateBuilder track(boolean value) {
        track = value;

        return self();
    }

    @Override
    protected void applyArguments() {
        if (force) {
            builder.argument("--force");
        }
        if (reflog) {
            builder.argument("--create-reflog");
        }
        if (track) {
            builder.argument("--track");
        } else {
            builder.argument("--no-track");
        }
        builder.argument("--"); //Ensure the name and startPoint are never treated as options
        builder.argument(name);
        if (StringUtils.isNotBlank(startPoint)) {
            builder.argument(startPoint);
        }
    }

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