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

import com.atlassian.bitbucket.mesh.git.builder.AbstractGitProcessBuilder;
import com.atlassian.bitbucket.mesh.git.builder.GitProcessBuilder;
import com.atlassian.bitbucket.mesh.repository.Repository;

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

import static java.util.Objects.requireNonNull;
import static org.apache.commons.lang3.StringUtils.isNotBlank;

public class DefaultGitLsRemoteBuilder
        extends AbstractGitProcessBuilder<GitLsRemoteBuilder>
        implements GitLsRemoteBuilder {

    private final List<String> patterns;

    private boolean quiet;
    private boolean refsOnly;
    private String targetRepository;

    public DefaultGitLsRemoteBuilder(GitProcessBuilder builder) {
        super(builder.command("ls-remote"));

        patterns = new ArrayList<>();
    }

    @Nonnull
    @Override
    public GitLsRemoteBuilder quiet(boolean value) {
        quiet = value;
        return self();
    }

    @Nonnull
    @Override
    public GitLsRemoteBuilder refs(String value, String... moreValues) {
        addIfNotBlank(patterns, value, moreValues);
        return self();
    }

    @Nonnull
    @Override
    public GitLsRemoteBuilder refs(Iterable<String> values) {
        addIfNotBlank(patterns, values);
        return self();
    }

    @Nonnull
    @Override
    public GitLsRemoteBuilder refsOnly(boolean value) {
        refsOnly = value;
        return self();
    }

    @Nonnull
    @Override
    public GitLsRemoteBuilder repository(@Nonnull Repository value) {
        requireNonNull(value, "repository");
        Repository repository = getRepository();
        if (repository == null) {
            targetRepository = value.getPath().toString();
        } else {
            targetRepository = repository.getPath().relativize(value.getPath()).toString();
        }
        return self();
    }

    @Nonnull
    @Override
    public GitLsRemoteBuilder repository(@Nonnull String remoteUrl) {
        targetRepository = requireNonBlank(remoteUrl, "remoteUrl");
        return self();
    }

    @Override
    protected void applyArguments() {
        if (refsOnly) {
            builder.argument("--refs");
        }
        if (quiet) {
            builder.argument("--quiet");
        }
        if (isNotBlank(targetRepository)) {
            builder.argument(targetRepository);
        } else if (getRepository() != null) {
            builder.argument(".");
        }
        patterns.forEach(builder::argument);
    }

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