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

import com.atlassian.bitbucket.mesh.git.GitProcessCompletionHandler;
import com.atlassian.bitbucket.mesh.git.exception.NoMergeBaseException;
import com.atlassian.bitbucket.mesh.process.ProcessSummary;

import javax.annotation.Nonnull;

import static org.apache.commons.lang3.StringUtils.isBlank;

public class MergeBaseCompletionHandler extends GitProcessCompletionHandler {
    
    private final boolean required;

    public MergeBaseCompletionHandler(boolean required) {
        this.required = required;
    }

    @Override
    public boolean isError(@Nonnull ProcessSummary summary) {
        if (hasNoMergeBase(summary)) {
            if (required) {
                //If a merge base is required, throw an exception
                throw new NoMergeBaseException();
            }

            //Otherwise, it's not an error for there to be no merge base; return false here and
            //allow the associated handler to return null
            return false;
        }

        return super.isError(summary);
    }

    private boolean hasNoMergeBase(ProcessSummary summary) {
        //Exit code 1 and no error message means that there is no merge base for the provided commits
        return summary.getExitCode() == 1 && isBlank(summary.getStderr()) && summary.getThrown() == null;
    }
}
