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

import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.ResourceBundle;

import woolpack.el.AbstractEL;
import woolpack.el.EL;
import woolpack.factory.FactoryUtils;
import woolpack.fn.Fn;
import woolpack.fn.FnUtils;

/**
 * ユーティリティです。
 * 型推論で表記を簡略するためのスタティックメソッドと変数を含みます。
 * 
 * @author nakamura
 * 
 */
public final class ConfigUtils {
	public static final ConfigGetter GET_CONFIG = new ConfigGetter();

	/**
	 * {@link ConfigContext}のアクセサにアクセスする{@link EL}です。
	 */
	public static final EL CONFIG_EL = new AbstractEL() {
		@Override
		public Object getValue(final Object root, final Class clazz) {
			return ((ConfigContext) root).getConfig();
		}
		@Override
		public boolean setValue(final Object root, final Object value) {
			((ConfigContext) root).setConfig((Map<String, Object>) value);
			return true;
		}
	};
	
	private ConfigUtils() {
	}

	/**
	 * 設定情報の{@link java.util.Map}をキャッシュする{@link Fn}を返します。
	 * @param <C>
	 * @param <E>
	 * @param maker 設定情報を生成する委譲先。
	 * @return 設定情報をキャッシュする{@link Fn}。
	 */
	public static <C extends ConfigContext, E extends Exception> Fn<C, Void, E> cache(final Fn<? super C, ?, ? extends E> maker) {
		return FactoryUtils.cache(
				FnUtils.<C, Map<String, Object>, E>fixThrows(new HashMap<String, Object>(1)),
				FnUtils.<C, String, E>fixThrows(""),
				maker,
				ConfigUtils.CONFIG_EL
		);
	}
	
	public static <C extends ConfigContext, E extends Exception> ConfigSetter<C, E> setConfig(final Fn<? super C, ? extends Map<String, Object>, ? extends E> fn) {
		return new ConfigSetter<C, E>(fn);
	}
	
	public static <C extends ConfigContext, E extends Exception> PutResourceBundle<C, E> putResourceBundle(
			final Fn<? super C, ? extends ResourceBundle, ? extends E> fn) {
		return new PutResourceBundle<C, E>(fn);
	}
	
	public static ResourceBundleFactory<RuntimeException> resourceBundleFactory(
			final String path,
			final ThreadLocal<Locale> threadLocal) {
		return new ResourceBundleFactory<RuntimeException>(path, threadLocal);
	}
	
	public static ToLinkedHashMap<RuntimeException> toLinkedHashMap(
			final String newMapListPosition,
			final String valueSourcePosition,
			final String labelSourcePosition,
			final String separator) {
		return new ToLinkedHashMap<RuntimeException>(newMapListPosition, valueSourcePosition, labelSourcePosition, separator);
	}
}
