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

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 com.atlassian.bitbucket.mesh.util.Version;

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

public class DefaultGitAddBuilder extends AbstractGitProcessBuilder<GitAddBuilder> implements GitAddBuilder {

    private static final Version VERSION_2_34 = new Version(2, 34);

    private final Set<String> paths;

    private boolean all;
    private boolean force;
    private boolean sparse;

    public DefaultGitAddBuilder(GitProcessBuilder builder) {
        super(builder.command("add"));

        paths = new LinkedHashSet<>();
    }

    @Nonnull
    @Override
    public GitAddBuilder all(boolean value) {
        all = value;

        return self();
    }

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

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

        return self();
    }

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

        return self();
    }

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

        return self();
    }

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

        return self();
    }

    @Nonnull
    @Override
    public GitAddBuilder sparse(boolean value) {
        sparse = value;

        return self();
    }

    @Override
    protected void applyArguments() {
        if (all) {
            builder.argument("-A");
        }
        if (force) {
            builder.argument("--force");
        }
        if (sparse && isGitVersionAtLeast(VERSION_2_34)) {
            builder.argument("--sparse");
        }
        builder.argument("--");
        paths.forEach(builder::rawArgument);
    }

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