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

import com.atlassian.bitbucket.mesh.git.GitConstants;
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 javax.annotation.Nonnull;

public class DefaultGitGcBuilder extends AbstractGitProcessBuilder<GitGcBuilder> implements GitGcBuilder {

    private boolean aggressive;
    private boolean auto;
    private boolean prune;
    private String pruneOlderThan;
    private boolean quiet;

    public DefaultGitGcBuilder(GitProcessBuilder builder) {
        //Don't invoke reference-transaction hooks when packing refs
        super(builder.command("gc").withConfiguration(GitConstants.CONFIG_CORE_HOOKS_PATH, ""));

        prune = true; //Default in git is to do --prune, not --no-prune
    }

    @Nonnull
    @Override
    public GitGcBuilder aggressive(boolean value) {
        aggressive = value;

        return self();
    }

    @Nonnull
    @Override
    public GitGcBuilder auto(boolean value) {
        auto = value;

        return self();
    }

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

    @Nonnull
    @Override
    public GitGcBuilder prune(boolean value) {
        prune = value;

        return self();
    }

    @Nonnull
    @Override
    public GitGcBuilder pruneOlderThan(String value) {
        pruneOlderThan = value;
        if (value != null) {
            prune = true;
        }

        return self();
    }

    @Nonnull
    @Override
    public GitGcBuilder quiet(boolean value) {
        quiet = value;

        return self();
    }

    @Override
    protected void applyArguments() {
        if (aggressive) {
            builder.argument("--aggressive");
        }
        if (auto) {
            builder.argument("--auto");
        }
        if (quiet) {
            builder.argument("--quiet");
        }

        if (prune) {
            if (pruneOlderThan != null) {
                builder.argument("--prune=" + pruneOlderThan);
            }
        } else {
            builder.argument("--no-prune");
        }
    }

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