/*
 * Copyright 2006 Takahiro Nakamura.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
 * either express or implied. See the License for the specific language
 * governing permissions and limitations under the License.
 */
package woolpack.validator;

import java.util.Collection;
import java.util.Map;

import woolpack.bool.BooleanState;
import woolpack.fn.Fn;

public class NameBranch<E extends Exception> implements Fn<ValidatorContext, Boolean, E> {
	private Fn<Object, ? extends BooleanState, ? extends RuntimeException> operator;
	private Map<String, ? extends Fn<? super ValidatorContext, Boolean, ? extends E>> map;

	public NameBranch(
			final Fn<Object, ? extends BooleanState, ? extends RuntimeException> operator,
			final Map<String, ? extends Fn<? super ValidatorContext, Boolean, ? extends E>> map) {
		this.operator = operator;
		this.map = map;
	}

	protected Collection<String> keySet(final ValidatorContext context) {
		return map.keySet();
	}

	public Boolean exec(final ValidatorContext context) throws E {
		final BooleanState state = operator.exec(null);
		for (final String key : keySet(context)) {
			state.in(new Fn<ValidatorContext, Boolean, E>() {
				public Boolean exec(final ValidatorContext context) throws E {
					final Fn<? super ValidatorContext, Boolean, ? extends E> e = map.get(key);
					if (e != null) {
						final String baseKey = context.getKey();
						try {
							context.setKey(key);
							return e.exec(context);
						} finally {
							context.setKey(baseKey);
						}
					} else {
						return true;
					}
				}
			}.exec(context));
			if (state.isStopped()) {
				break;
			}
		}
		return state.isCurrent();
	}

	public Map<String, ? extends Fn<? super ValidatorContext, Boolean, ? extends E>> getMap() {
		return map;
	}
	public void setMap(final Map<String, ? extends Fn<? super ValidatorContext, Boolean, ? extends E>> map) {
		this.map = map;
	}
	public Fn<Object, ? extends BooleanState, ? extends RuntimeException> getOperator() {
		return operator;
	}
	public void setOperator(final Fn<Object, ? extends BooleanState, ? extends RuntimeException> operator) {
		this.operator = operator;
	}
}
