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

import woolpack.utils.CheckUtils;
import woolpack.utils.Switchable;
import woolpack.validator.ValidatorContext;
import woolpack.validator.ValidatorExpression;

/**
 * 現在のスレッドの{@link Locale}で委譲先を分岐する{@link ValidatorExpression}。
 * 適用しているパターン：フィルタ。
 * 
 * @author nakamura
 * 
 */
public class BranchByLocaleValidator implements ValidatorExpression {
	private final Switchable<Locale, ValidatorExpression> switchable;

	private final ThreadLocal<Locale> threadLocal;

	/**
	 * コンストラクタ。
	 * 
	 * @param switchable
	 *            {@link Locale}と委譲先の{@link Switchable}。
	 * @param threadLocal
	 *            現在のスレッドの{@link Locale}を保持する
	 *            {@link ThreadLocal}。本クラスはこの引数の状態を変化させない。
	 * @throws NullPointerException
	 *             引数のいずれかが null の場合。
	 */
	public BranchByLocaleValidator(
			final Switchable<Locale, ValidatorExpression> switchable,
			final ThreadLocal<Locale> threadLocal) {
		CheckUtils.checkNotNull(switchable);
		CheckUtils.checkNotNull(threadLocal);
		this.switchable = switchable;
		this.threadLocal = threadLocal;
	}

	/**
	 * @throws NullPointerException
	 *             ロケールに対する{@link ValidatorContext}が存在しない場合。
	 */
	public boolean interpret(final ValidatorContext context) {
		return switchable.get(threadLocal.get()).interpret(context);
	}

	public Switchable<Locale, ValidatorExpression> getSwitchable() {
		return switchable;
	}

	public ThreadLocal<Locale> getThreadLocal() {
		return threadLocal;
	}
}
