package com.atlassian.stash.internal.scm.git.command.updateref;

import com.atlassian.bitbucket.i18n.I18nService;
import com.atlassian.bitbucket.repository.Repository;
import com.atlassian.bitbucket.scm.CommandExitHandler;
import com.atlassian.bitbucket.scm.CommandOutputHandler;
import com.atlassian.bitbucket.scm.git.command.GitCommand;
import com.atlassian.bitbucket.scm.git.command.GitScmCommandBuilder;
import com.atlassian.bitbucket.scm.git.command.updateref.GitUpdateRefDeleteBuilder;

import javax.annotation.Nonnull;

/**
 * @since 1.3
 */
public class DefaultGitUpdateRefDeleteBuilder
        extends AbstractGitUpdateRefBuilder<GitUpdateRefDeleteBuilder>
        implements GitUpdateRefDeleteBuilder {

    private final I18nService i18nService;
    private final Repository repository;

    private boolean useDefaultExitHandler;

    public DefaultGitUpdateRefDeleteBuilder(GitScmCommandBuilder builder, I18nService i18nService,
                                            Repository repository, String ref) {
        super(builder, ref);

        this.i18nService = i18nService;
        this.repository = repository;

        useDefaultExitHandler = true;
    }

    @Nonnull
    @Override
    public <T> GitCommand<T> build(@Nonnull CommandOutputHandler<T> outputHandler) {
        if (useDefaultExitHandler) {
            builder.exitHandler(new DeleteUpdateRefCommandExitHandler(i18nService, repository));
        }

        return super.build(outputHandler);
    }

    @Nonnull
    @Override
    public GitUpdateRefDeleteBuilder defaultExitHandler() {
        useDefaultExitHandler = true;

        return self();
    }

    @Nonnull
    @Override
    public GitUpdateRefDeleteBuilder exitHandler(@Nonnull CommandExitHandler value) {
        super.exitHandler(value);

        useDefaultExitHandler = false;

        return self();
    }

    @Override
    protected void applyRefArguments(String ref) {
        builder.argument("-d")
                .argument(ref);
    }

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