/*
 * 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.io.Reader;
import java.util.Locale;
import java.util.Map;

import woolpack.utils.ReaderFactory;

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

	/**
	 * @throws NullPointerException ロケールに対する{@link ReaderFactory}が存在しない場合。
	 */
	public Reader newInstance(final String id) throws IOException {
		final Locale l0 = threadLocal.get();
		final Locale l1 = LocaleConstants.search(map.keySet(), l0);
		return map.get(l1).newInstance(id);
	}
}
