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

import com.atlassian.bitbucket.mesh.git.GitTagType;
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 java.util.Objects.requireNonNull;

public class DefaultGitTagCreateBuilder
        extends AbstractGitProcessBuilder<GitTagCreateBuilder>
        implements GitTagCreateBuilder {

    private final String name;

    private boolean force;
    private String message;
    private String startPoint;
    private GitTagType type;

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

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

        type = GitTagType.ANNOTATED;
    }

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

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

        return self();
    }

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

        return self();
    }

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

        return self();
    }

    @Nonnull
    @Override
    public GitTagCreateBuilder type(@Nonnull GitTagType value) {
        type = requireNonNull(value, "type");

        return self();
    }

    @Override
    protected void applyArguments() {
        if (GitTagType.ANNOTATED.equals(type)) {
            builder.argument("-a");
            builder.argument("-m");
            if (StringUtils.isBlank(message)) {
                builder.argument("Tagged " + startPoint);
            } else {
                builder.argument(message);
            }
        }
        if (force) {
            builder.argument("-f");
        }
        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 GitTagCreateBuilder self() {
        return this;
    }
}
