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

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

import javax.annotation.Nonnull;
import java.nio.file.Path;

import static com.google.common.base.Preconditions.checkState;
import static java.util.Objects.requireNonNull;

public class DefaultGitReceivePackBuilder
        extends AbstractGitProcessBuilder<GitReceivePackBuilder>
        implements GitReceivePackBuilder {

    private boolean advertiseRefs;
    private Path directory;
    private boolean statelessRpc;

    public DefaultGitReceivePackBuilder(GitProcessBuilder builder, Path directory) {
        super(builder.command("receive-pack"));

        //Default to the repository's directory, if one was set, so callers don't need to redundantly
        //pass it to directory(Path)
        this.directory = directory;
    }

    @Nonnull
    @Override
    public GitReceivePackBuilder advertiseRefs(boolean value) {
        advertiseRefs = value;

        return self();
    }

    @Nonnull
    @Override
    public GitReceivePackBuilder directory(@Nonnull Path value) {
        directory = requireNonNull(value, "directory");

        return self();
    }

    @Nonnull
    @Override
    public GitReceivePackBuilder statelessRpc(boolean value) {
        statelessRpc = value;

        return self();
    }

    @Override
    protected void applyArguments() {
        checkState(directory != null, "git receive-pack requires a path");

        if (advertiseRefs) {
            builder.argument("--advertise-refs");
        }
        if (statelessRpc) {
            builder.argument("--stateless-rpc");
        }
        builder.rawArgument(directory.toString());
    }

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