/*
 * This file is part of Nuts Framework.
 * Copyright(C) 2009-2012 Nuts Develop Team.
 *
 * Nuts Framework is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License any later version.
 *
 * Nuts Framework is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.	 See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Nuts Framework. If not, see <http://www.gnu.org/licenses/>.
 */
package nuts.core.json.filters;

import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

import net.sf.json.util.PropertyFilter;

public abstract class MappingPropertyFilter implements PropertyFilter {
	private Map<String, PropertyFilter> filters = new HashMap<String, PropertyFilter>();

	public MappingPropertyFilter() {
		this(null);
	}

	public MappingPropertyFilter(Map<String, PropertyFilter> filters) {
		if (filters != null) {
			this.filters.putAll(filters);
		}
	}

	public void addPropertyFilter(String target, PropertyFilter filter) {
		if (filter != null) {
			filters.put(target, filter);
		}
	}

	public boolean apply(Object source, String name, Object value) {
		for (Entry<String, PropertyFilter> entry : filters.entrySet()) {
			String key = entry.getKey();
			if (keyMatches(key, source, name, value)) {
				PropertyFilter filter = entry.getValue();
				return filter.apply(source, name, value);
			}
		}
		return false;
	}

	public void removePropertyFilter(String target) {
		if (target != null) {
			filters.remove(target);
		}
	}

	protected abstract boolean keyMatches(String key, Object source, String name, Object value);
}
