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

import java.util.Locale;

import woolpack.fn.Fn;
import woolpack.fn.SwitchFn;

/**
 * 一覧から指定されたロケールに最も近いロケールをキーとして値を返す{@link Fn}です。
 * @author nakamura
 *
 * @param <R>
 */
public class SwitchNearLocale<R> implements Fn<Locale, R> {
	private static final int LOCALE_DEPTH = 3;
	
	private SwitchFn<Locale, ? extends R> switching;
	
	public SwitchNearLocale(final SwitchFn<Locale, ? extends R> switching) {
		this.switching = switching;
	}
	
	private static int calcLocaleCount(final Locale key) {
		return (key.getVariant() != null && key.getVariant().length() > 0)
		? LOCALE_DEPTH
				: (key.getCountry() != null
						&& key.getCountry().length() > 0) ? 2
						: 1;
	}

	public R exec(final Locale c) {
		{
			final R r = switching.getMap().get(c);
			if (r != null) {
				return r;
			}
		}
		if (c == null) {
			return switching.getDefaultFn().exec(c);
		}
		
		final int keyCount = calcLocaleCount(c);

		Locale l0 = null;
		int count0 = 0;
		for (final Object object : switching.getMap().keySet()) {
			if (!(object instanceof Locale)) {
				continue;
			}
			final Locale l1 = (Locale) object;
			if (keyCount < calcLocaleCount(l1)) {
				continue;
			}
			int count1 = 0;
			if (c.getLanguage() != null
					&& c.getLanguage().equals(l1.getLanguage())) {
				count1++;
				if (c.getCountry() != null
						&& c.getCountry().equals(l1.getCountry())) {
					count1++;
				}
			}
			if (count0 < count1) {
				count0 = count1;
				l0 = l1;
			}
		}
		if (l0 == null) {
			return switching.getDefaultFn().exec(c);
		}
		return switching.exec(l0);
	}

	public SwitchFn<Locale, ? extends R> getSwitching() {
		return switching;
	}
	public void setSwitching(final SwitchFn<Locale, ? extends R> switching) {
		this.switching = switching;
	}
}
