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

import com.atlassian.bitbucket.commit.NoSuchCommitException;
import com.atlassian.bitbucket.i18n.I18nService;
import com.atlassian.bitbucket.repository.Repository;
import com.atlassian.bitbucket.scm.git.command.GitCommandExitHandler;
import com.google.common.base.Joiner;
import com.google.common.collect.Iterables;

import javax.annotation.Nonnull;
import java.util.Set;
import java.util.stream.Stream;

import static com.atlassian.bitbucket.util.MoreCollectors.toImmutableSet;

/**
 * Handles the error output generated by the rev-list command, mapping missing commits to  
 *
 * @since 4.5
 */
public class RevCoreExitHandler extends GitCommandExitHandler {

    private final boolean ignoreMissing;
    private final Set<String> revs;

    public RevCoreExitHandler(@Nonnull I18nService i18nService, @Nonnull Repository repository,
                              @Nonnull Set<String> includes, @Nonnull Set<String> excludes,
                              boolean ignoreMissing) {
        super(i18nService, repository);

        this.ignoreMissing = ignoreMissing;

        revs = Stream.concat(includes.stream().limit(3), excludes.stream().limit(3))
                .collect(toImmutableSet());
    }

    @Override
    protected void onError(String command, int exitCode, String stdErr, Throwable thrown) {
        if (stdErr.startsWith("usage")) {
            if (ignoreMissing) {
                return;
            }
            if (!revs.isEmpty()) {
                //noinspection ConstantConditions
                throw new NoSuchCommitException(
                        i18nService.createKeyedMessage("bitbucket.service.repository.commitsnotfound",
                                repository.getName(), Joiner.on(", ").join(revs)),
                        Iterables.getFirst(revs, null));
            }
        }

        super.onError(command, exitCode, stdErr, thrown);
    }
}