/**
 * Copyright (c) 2000-2017 Liferay, Inc. All rights reserved.
 *
 * The contents of this file are subject to the terms of the Liferay Enterprise
 * pSubscription License ("License"). You may not use this file except in
 * compliance with the License. You can obtain a copy of the License by
 * contacting Liferay, Inc. See the License for the specific language governing
 * permissions and limitations under the License, including but not limited to
 * distribution rights of the Software.
 *
 *
 *
 */

package com.liferay.portal.kernel.util;

import com.liferay.portal.kernel.configuration.Filter;
import com.liferay.portal.kernel.log.Log;
import com.liferay.portal.kernel.log.LogFactoryUtil;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

import java.text.Collator;
import java.text.ParseException;
import java.text.RuleBasedCollator;

import java.util.Locale;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author Preston Crary
 */
public class CollatorUtil {

	public static Collator getInstance(Locale locale) {
		String rules = _rules.get(locale);

		if (rules == null) {
			String languageId = LocaleUtil.toLanguageId(locale);

			rules = PropsUtil.get("collator.rules", new Filter(languageId));

			if (Validator.isNull(rules)) {
				rules = StringPool.BLANK;
			}
			else if (rules.startsWith("file:")) {
				InputStream is = null;

				try {
					is = new FileInputStream(rules.substring(5));

					rules = StringUtil.read(is);
				}
				catch (Exception e) {
					_log.error(e, e);

					rules = StringPool.BLANK;
				}
				finally {
					try {
						if (is != null) {
							is.close();
						}
					}
					catch (IOException ioe) {
					}
				}
			}

			_rules.put(locale, rules);
		}

		if (!rules.equals(StringPool.BLANK)) {
			try {
				return new RuleBasedCollator(rules);
			}
			catch (ParseException pe) {
				_log.error(pe, pe);

				_rules.put(locale, StringPool.BLANK);
			}
		}

		return Collator.getInstance(locale);
	}

	private static Log _log = LogFactoryUtil.getLog(CollatorUtil.class);

	private static final Map<Locale, String> _rules =
		new ConcurrentHashMap<Locale, String>();

}