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

import woolpack.text.FormatFactory;

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

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