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

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

import javax.annotation.Nonnull;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class DeleteBranchCompletionHandler extends GitProcessCompletionHandler {

    public static final Pattern PATTERN_BRANCH_NOT_FOUND = Pattern.compile("error: branch '(.+)' not found\\.");

    public static final Pattern PATTERN_BRANCH_NOT_MERGED = Pattern.compile("error: The branch '(.+)' is not fully merged\\.$", Pattern.MULTILINE);

    @Override
    protected void evaluateStderr(@Nonnull ProcessSummary summary, @Nonnull String stderr) {
        Matcher matcher = PATTERN_BRANCH_NOT_FOUND.matcher(stderr);
        if (matcher.matches()) {
            throw new ObjectNotFoundException(matcher.group(1));
        }

        matcher = PATTERN_BRANCH_NOT_MERGED.matcher(stderr);
        if (matcher.find()) {
            throw new BranchNotMergedException(matcher.group(1));
        }

        super.evaluateStderr(summary, stderr);
    }
}
