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

import com.atlassian.bitbucket.mesh.git.builder.AbstractGitProcessBuilder;
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;

import static com.google.common.base.Preconditions.checkArgument;

public class DefaultGitStatusBuilder extends AbstractGitProcessBuilder<GitStatusBuilder> implements GitStatusBuilder {

    private final Set<String> paths;

    private boolean porcelain;
    private boolean shorten;
    private String untracked;

    public DefaultGitStatusBuilder(GitProcessBuilder builder) {
        super(builder.command("status"));

        paths = new LinkedHashSet<>();
    }

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

        return self();
    }

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

        return self();
    }

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

        return self();
    }

    @Nonnull
    @Override
    public GitStatusBuilder porcelain(boolean value) {
        porcelain = value;

        return self();
    }

    @Nonnull
    @Override
    public GitStatusBuilder shorten(boolean value) {
        shorten = value;

        return self();
    }

    @Nonnull
    @Override
    public GitStatusBuilder untracked(String value) {
        checkArgument("no".equals(value) || "normal".equals(value) || "all".equals(value));
        untracked = value;

        return self();
    }

    @Override
    protected void applyArguments() {
        if (porcelain) {
            builder.argument("--porcelain");
        }
        if (shorten) {
            builder.argument("--short");
        }
        if (StringUtils.isNotBlank(untracked)) {
            builder.argument("-u" + untracked);
        }
        builder.argument("--");
        paths.forEach(builder::rawArgument);
    }

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