package com.atlassian.stash.internal.scm.git.command.reset;

import com.atlassian.stash.internal.scm.git.command.AbstractGitCommandBuilder;
import com.atlassian.bitbucket.scm.git.command.GitCommand;
import com.atlassian.bitbucket.scm.git.command.GitScmCommandBuilder;
import com.atlassian.bitbucket.scm.git.command.reset.GitResetBuilder;
import com.google.common.collect.Sets;
import org.apache.commons.lang3.StringUtils;

import javax.annotation.Nonnull;
import java.util.Set;

/**
 * @since 1.3
 */
public class DefaultGitResetBuilder extends AbstractGitCommandBuilder<GitResetBuilder> implements GitResetBuilder {

    private final Set<String> paths;

    private GitResetMode mode;
    private String commit;
    private boolean quiet;

    public DefaultGitResetBuilder(GitScmCommandBuilder builder) {
        super(builder.command("reset"));

        paths = Sets.newHashSet();
    }

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

    @Nonnull
    @Override
    public GitResetBuilder commit(String value) {
        commit = value;

        return self();
    }

    @Nonnull
    @Override
    public GitResetBuilder hard() {
        mode = GitResetMode.HARD;

        return this;
    }

    @Nonnull
    @Override
    public GitResetBuilder mixed() {
        mode = GitResetMode.MIXED;

        return this;
    }

    @Nonnull
    @Override
    public GitResetBuilder path(String value) {
        addIfNotBlank(paths, value);

        return self();
    }

    @Nonnull
    @Override
    public GitResetBuilder paths(Iterable<String> values) {
        addIfNotBlank(paths, values);

        return self();
    }

    @Nonnull
    @Override
    public GitResetBuilder paths(String value, String... values) {
        addIfNotBlank(paths, value, values);

        return self();
    }

    @Nonnull
    @Override
    public GitResetBuilder quiet(boolean value) {
        quiet = value;

        return self();
    }

    @Nonnull
    @Override
    public GitResetBuilder soft() {
        mode = GitResetMode.SOFT;

        return this;
    }

    @Override
    protected void applyArguments() {
        if (mode != null) {
            builder.argument(mode.getFlag());
        }
        if (quiet) {
            builder.argument("--quiet");
        }
        if (StringUtils.isNotBlank(commit)) {
            builder.argument(commit);
        }
        builder.argument("--");
        for (String path : paths) {
            builder.argument(path);
        }
    }

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