/**
 {copyright}
 */

package com.{company}.{initiative}.common;

import java.util.concurrent.ConcurrentHashMap;

import javax.wbem.WBEMException;

public class IndicationManager {

	private final IndicationHandler mImplementation;
	private final ConcurrentHashMap<String, Integer> mSubscriptionList;

	public IndicationManager(IndicationHandler impl) {
		mImplementation = impl;
		mSubscriptionList = new ConcurrentHashMap<String, Integer>();
	}

	public void authorize(final String pIndicationFilter) throws WBEMException {
		// first get string where there are not 2 or more spaces together
		String indicationFilter = collapseSpaces(pIndicationFilter);
		if (null == indicationFilter) {
			throw new IllegalArgumentException();
		}
		String[] mSupportedIndicationFilters = mImplementation
				.getSupportedIndications();
		if (null != mSupportedIndicationFilters) {
			for (String filter : mSupportedIndicationFilters) {
				if (filter.equalsIgnoreCase(indicationFilter)) {
					return;
				}
			}
		}
		throw new WBEMException(WBEMException.CIM_ERR_NOT_SUPPORTED);
	}

	public synchronized int activate(final String pIndicationFilter) {
		// first get string where there are not 2 or more spaces together
		String indicationFilter = collapseSpaces(pIndicationFilter);
		int newNumSubscriptions = 1;
		Integer numSubscriptions = mSubscriptionList.get(indicationFilter);
		if (null != numSubscriptions) {
			newNumSubscriptions = numSubscriptions.intValue() + 1;
		}
		mSubscriptionList.put(indicationFilter,
				new Integer(newNumSubscriptions));
		return newNumSubscriptions;
	}

	public synchronized int deactivate(final String pIndicationFilter) {
		// first get string where there are not 2 or more spaces together
		String indicationFilter = collapseSpaces(pIndicationFilter);
		// default value to set will be null (remove filter)
		int newNumSubscriptions = 0;
		Integer numSubscriptions = mSubscriptionList.get(indicationFilter);
		// if we more than 1 active subscriptions for this filter,
		// set new number to be 1 less than current number
		if (null != numSubscriptions && numSubscriptions.intValue() > 1) {
			newNumSubscriptions = numSubscriptions.intValue() - 1;
		} 
		if (0 == newNumSubscriptions) {
			// if we have no more activations for this filter, remove from hash
			mSubscriptionList.remove(indicationFilter);
		} else {
			// set new activations count
			mSubscriptionList.put(indicationFilter, new Integer(newNumSubscriptions));			
		}
		return newNumSubscriptions;
	}

	/**
	 * Takes a String and returns that same string but with no consecutive space
	 * characters and no leading or trailing spaces
	 * 
	 * @param pString
	 *            String to collapse spaces on
	 * @return Source string but with no consecutive space characters and no
	 *         leading or trailing spaces
	 */
	public static String collapseSpaces(String pString) {
		return pString.replaceAll("\\s+", " ").trim();
	}
	

}
