/*
 * 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.locale;

import java.io.IOException;
import java.util.Collection;
import java.util.Locale;
import java.util.Map;

import woolpack.validator.ValidatorConstants;
import woolpack.validator.ValidatorContext;
import woolpack.validator.ValidatorExpression;
import woolpack.validator.ValidatorExpressionAdapter;

/**
 * 現在のスレッドの{@link Locale}で委譲先を分岐する{@link ValidatorExpression}。
 * @author nakamura
 *
 */
public class BranchByLocaleValidator extends ValidatorExpressionAdapter {
	private final Map<Locale,ValidatorExpression> map;
	private final ThreadLocal<Locale> threadLocal;
	
	/**
	 * コンストラクタ。
	 * @param map {@link Locale}と委譲先の{@link Map}。ステートレスであるべき。
	 * @param threadLocal 現在のスレッドの{@link Locale}を保持する{@link ThreadLocal}。
	 * @throws NullPointerException 引数のいずれかが null の場合。
	 */
	public BranchByLocaleValidator(final Map<Locale,ValidatorExpression> map, final ThreadLocal<Locale> threadLocal){
		map.getClass();
		threadLocal.getClass();
		this.map = map;
		this.threadLocal = threadLocal;
	}

	@Override public boolean interpret(final ValidatorContext context) {
		final Locale l0 = threadLocal.get();
		final Locale l1 = LocaleConstants.search(map.keySet(), l0);
		return map.get(l1).interpret(context);
	}

	@Override public void appendArgumentTo(final Appendable sb) throws IOException{
		ValidatorConstants.appendTo(sb, map);
	}

	@Override public void addMessageTo(final Collection<String> messageCollection) {
		for(final Locale key:map.keySet()){
			final ValidatorExpression expression = map.get(key);
			expression.addMessageTo(messageCollection);
		}
	}

}
