package eu.dnetlib.enabling.is.sn;

import java.util.Collection;

import org.apache.oro.text.perl.Perl5Util;

/**
 * Provides common functionality for subscription registries.
 * 
 * @author marko
 * 
 */
public abstract class AbstractSubscriptionRegistry {

	/**
	 * prefix position in regular expression.
	 */
	private static final int PREFIX_POSITION = 1;
	
	/**
	 * rest of string position in regular expression.
	 */
	private static final int REST_POSITION = 3;
	
	/**
	 * Return true if the subscription prefix is acceptable.
	 * 
	 * Topic expressions are made of slash-delimited components. The "prefix" here is the first slash (/) delimited
	 * string of the topic expression.
	 * 
	 * TODO: stupid implementation.
	 * 
	 * @param subscription
	 *            subscription request
	 * @return true if accepted
	 */
	protected TopicExpressionMatchResult matchPrefix(final SubscriptionRequest subscription) {
		final Perl5Util matcher = new Perl5Util(); // NOPMD
		
		for (String prefix : getAcceptedPrefixes())
			if (matcher.match("/^(" + prefix + ")($|/)(.*)$/", subscription.getTopicExpression())) {
				return new TopicExpressionMatchResult(matcher.getMatch().group(PREFIX_POSITION), matcher.getMatch().group(REST_POSITION));
			}
		return null;
	}

	/**
	 * A collection of accepted prefixes.
	 * 
	 * @return prefix list
	 */
	protected abstract Collection<String> getAcceptedPrefixes();
}
