package com.atlassian.bitbucket.mesh.git.hook;

import com.google.common.io.LineProcessor;

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

public abstract class AbstractRefUpdateParser<T> implements LineProcessor<T> {

    private static final int GROUP_NEW_HASH = 2;
    private static final int GROUP_OLD_HASH = 1;
    private static final int GROUP_REF_ID = 3;
    private static final Pattern PATTERN_REF_CHANGE = Pattern.compile("([a-f0-9]{40}) ([a-f0-9]{40}) (.*)");

    @Override
    public boolean processLine(@Nonnull String line) {
        Matcher matcher = PATTERN_REF_CHANGE.matcher(line);
        if (matcher.matches()) {
            return processRefUpdate(
                    matcher.group(GROUP_REF_ID),
                    matcher.group(GROUP_OLD_HASH),
                    matcher.group(GROUP_NEW_HASH));
        }

        return true;
    }

    protected abstract boolean processRefUpdate(String refId, String oldHash, String newHash);
}
