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

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;

public abstract class AbstractGitUpdateRefBuilder<B extends GitUpdateRefBuilderSupport<B>>
        extends AbstractGitProcessBuilder<B>
        implements GitUpdateRefBuilderSupport<B> {

    private final String ref;

    private boolean deref;
    private String message;
    private String oldValue;

    public AbstractGitUpdateRefBuilder(GitProcessBuilder builder, String ref) {
        super(builder);

        this.ref = requireNonBlank(ref, "ref");

        deref = true;
    }

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

    @Nonnull
    @Override
    public B deref(boolean value) {
        deref = value;

        return self();
    }

    @Nonnull
    @Override
    public B message(String value) {
        message = value;

        return self();
    }

    @Nonnull
    @Override
    public B oldValue(String value) {
        oldValue = value;

        return self();
    }

    @Override
    protected void applyArguments() {
        if (StringUtils.isNotBlank(message)) {
            builder.argument("-m").argument(message);
        }
        if (!deref) {
            builder.argument("--no-deref");
        }

        applyRefArguments(ref);

        if (StringUtils.isNotBlank(oldValue)) {
            builder.commitish(oldValue);
        }
    }

    protected abstract void applyRefArguments(String ref);
}
