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

import woolpack.utils.Switchable;

/**
 * 静的メソッドの集まり。
 * @author nakamura
 *
 */
public class LocaleConstants {

	private LocaleConstants(){}// カバレージがここを通過してはいけない
	
	private static int calcLocaleCount(final Locale key){
		return (key.getVariant()!=null && key.getVariant().length() > 0)?3:(key.getCountry()!=null && key.getCountry().length() > 0)?2:1;
	}
	
	/**
	 * 一覧から指定されたロケールに最も近いロケールをキーとして値を返す{@link Switchable}を返す。
	 * @param <V> 値。
	 * @param switchable スイッチ。
	 * @return 一覧から指定されたロケールにもっとも近いロケールをキーとして値を返す{@link Switchable}。
	 */
	public static <V> Switchable<Locale,V> nearLocaleSwitch(final Switchable<Locale,V> switchable){
		return new Switchable<Locale,V>(){
			public V get(final Locale key) {
				if(switchable.keys().contains(key)){
					return switchable.get(key);
				}
				if(key == null){
					return switchable.getDefault();
				}
				final int keyCount = calcLocaleCount(key);
				
				Locale l0 = null;
				int count0 = 0;
				for(final Locale l1:switchable.keys()){
					if(keyCount < calcLocaleCount(l1)){
						continue;
					}
					int count1 = 0;
					if(key.getLanguage() != null && key.getLanguage().equals(l1.getLanguage())){
						count1++;
						if(key.getCountry() != null && key.getCountry().equals(l1.getCountry())){
							count1++;
						}
					}
					if(count0 < count1){
						count0 = count1;
						l0 = l1;
					}
				}
				if(l0 == null){
					return switchable.getDefault();
				}
				return switchable.get(l0);
			}
			public Collection<Locale> keys() {
				return switchable.keys();
			}
			public V getDefault() {
				return switchable.getDefault();
			}
		};
	}
}
