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

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 java.util.LinkedHashSet;
import java.util.Set;

public class DefaultGitResetBuilder extends AbstractGitProcessBuilder<GitResetBuilder> implements GitResetBuilder {

    private final Set<String> paths;

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

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

        paths = new LinkedHashSet<>();
    }

    @Nonnull
    @Override
    public GitProcess<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.commitish(commit);
        }
        builder.argument("--");
        paths.forEach(builder::rawArgument);
    }

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