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

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

	private LocaleConstants(){
	}
	
	/**
	 * 一覧から指定されたロケールにもっとも近いロケールを返す。
	 * @param collection 検索対象。
	 * @param locale 検索条件。
	 * @return 検索結果。
	 * @throws NullPointerException collection が null の場合。
	 */
	public static Locale search(final Collection<Locale> collection, final Locale locale){
		// locale が null で collection に null が含まれるならそれが返される。
		if(collection.contains(locale)){
			return locale;
		}
		// locale が null なら collection の最初の値が返される。
		if(locale == null){
			return collection.iterator().next();
		}
		Locale l0 = null;
		int count0 = -1;
		for(final Locale l1:collection){
			if(l1 == null){
				continue;
			}
			int count1 = -1;
			if(locale.getLanguage() != null && locale.getLanguage().equals(l1.getLanguage())){
				count1++;
				if(locale.getCountry() != null && locale.getCountry().equals(l1.getCountry())){
					count1++;
				}
			}
			if(count0 < count1){
				count0 = count1;
				l0 = l1;
			}
		}
		if(count0 < 0){
			return collection.iterator().next();
		}
		return l0;
	}
}
