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

import com.atlassian.bitbucket.mesh.git.GitProcessCompletionHandler;
import com.atlassian.bitbucket.mesh.git.exception.RevertConflictedException;
import com.atlassian.bitbucket.mesh.git.exception.InvalidParentNumberException;
import com.atlassian.bitbucket.mesh.git.revert.RevertParameters;
import com.atlassian.bitbucket.mesh.process.ProcessSummary;

import javax.annotation.Nonnull;

import static java.util.Locale.ROOT;
import static java.util.Objects.requireNonNull;

public class RevertCompletionHandler extends GitProcessCompletionHandler {

    private final RevertParameters parameters;

    public RevertCompletionHandler(@Nonnull RevertParameters parameters) {
        this.parameters = requireNonNull(parameters, "parameters");
    }

    @Override
    protected void evaluateStderr(@Nonnull ProcessSummary summary, @Nonnull String stderr) {
        String commitId = parameters.getCommitId();

        if (stderr.toLowerCase(ROOT).contains("after resolving the conflicts")) {
            throw new RevertConflictedException(commitId, parameters.getBranch());
        }

        if (stderr.toLowerCase(ROOT).contains("error: commit " + commitId + " does not have parent")) {
            throw new InvalidParentNumberException(commitId,
                    parameters.getMergedCommitParentNumber().orElse(0));
        }

        super.evaluateStderr(summary, stderr);
    }
}