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

 import com.atlassian.bitbucket.repository.NoSuchBranchException;
 import com.atlassian.bitbucket.i18n.I18nService;
 import com.atlassian.bitbucket.repository.Repository;
 import com.atlassian.bitbucket.scm.git.command.GitCommandExitHandler;
 import com.atlassian.bitbucket.scm.git.command.branch.GitBranchNotMergedException;

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

public class DeleteBranchCommandExitHandler extends GitCommandExitHandler {

    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);

    public DeleteBranchCommandExitHandler(@Nonnull I18nService i18nService, @Nullable Repository repository) {
        super(i18nService, repository);
    }

    @Override
    protected void evaluateStdErr(String stdErr, String command) {
        Matcher matcher = PATTERN_BRANCH_NOT_FOUND.matcher(stdErr);
        if (matcher.matches()) {
            throwNoSuchBranchException(matcher.group(1));
        }

        matcher = PATTERN_BRANCH_NOT_MERGED.matcher(stdErr);
        if (matcher.find()) {
            throw new GitBranchNotMergedException(i18nService.createKeyedMessage("bitbucket.service.repository.branchnotmerged", matcher.group(1)));
        }

        super.evaluateStdErr(stdErr, command);
    }

    private void throwNoSuchBranchException(String branch) {
        if (repository == null) {
            throw new NoSuchBranchException(i18nService.createKeyedMessage("bitbucket.service.repository.branchnotfound.generic", branch), branch);
        }
        throw new NoSuchBranchException(i18nService.createKeyedMessage("bitbucket.service.repository.branchnotfound", branch, repository.getName()), branch);
    }
}
