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

import com.atlassian.bitbucket.mesh.git.builder.AbstractGitProcessBuilder;
import com.atlassian.bitbucket.mesh.git.builder.GitProcessBuilder;
import com.google.common.collect.ImmutableList;
import org.apache.commons.lang3.StringUtils;

import javax.annotation.Nonnull;
import java.util.Collections;
import java.util.List;

public class DefaultGitForEachRefBuilder
        extends AbstractGitProcessBuilder<GitForEachRefBuilder>
        implements GitForEachRefBuilder {

    private int count;
    private String format;
    private List<String> patterns;
    private String sort;

    public DefaultGitForEachRefBuilder(GitProcessBuilder builder) {
        super(builder.command("for-each-ref"));

        patterns = Collections.emptyList();
    }

    @Nonnull
    @Override
    public GitForEachRefBuilder count(int value) {
        count = value;

        return self();
    }

    @Nonnull
    @Override
    public GitForEachRefBuilder format(String value) {
        format = value;

        return self();
    }

    @Nonnull
    @Override
    public GitForEachRefBuilder pattern(String value) {
        return patterns(value);
    }

    @Nonnull
    @Override
    public GitForEachRefBuilder patterns(String value, String... values) {
        if (value == null) {
            patterns = Collections.emptyList();
        } else {
            patterns = ImmutableList.<String>builder()
                    .add(value)
                    .add(values)
                    .build();
        }

        return self();
    }

    @Nonnull
    @Override
    public GitForEachRefBuilder patterns(Iterable<String> values) {
        if (values != null) {
            patterns = ImmutableList.<String>builder()
                    .addAll(values)
                    .build();
        }

        return self();
    }

    @Nonnull
    @Override
    public GitForEachRefBuilder sort(String value) {
        sort = value;

        return self();
    }

    @Override
    protected void applyArguments() {
        if (count > 0) {
            builder.argument("--count=" + count);
        }
        if (StringUtils.isNotBlank(sort)) {
            builder.argument("--sort=" + sort);
        }
        if (StringUtils.isNotBlank(format)) {
            builder.argument("--format=" + format);
        }

        for (String pattern : patterns) {
            builder.argument(pattern);
        }
    }

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