/*
 * Copyright (c) 2003, Morpho Project.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice,
 *    this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 *    this list of conditions and the following disclaimer in the documentation
 *    and/or other materials provided with the distribution.
 * 3. Neither the name of the Morpho Project nor the names of its contributors
 *    may be used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */
package jp.morpho.webapp.resource;

import java.lang.reflect.Method;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Locale;
import java.util.ResourceBundle;
import java.util.logging.Level;
import java.util.logging.Logger;

import jp.morpho.webapp.Plugin;
import jp.morpho.webapp.PluginContext;
import jp.morpho.webapp.PluginException;
import jp.morpho.webapp.PluginKeys;

/**
 * @author Kumiko Hiroi
 */
public class MessageResourceManager
	implements Plugin
{

	private static final String fieldNameBaseKey = "fieldName.";

	protected ArrayList resourceEntries = new ArrayList();

	public MessageResourceManager()
	{
		super();
	}

	public synchronized void addMessageResourceEntry(MessageResourceEntry resourceEntry)
	{
		resourceEntries.add(resourceEntry);
	}

	public synchronized String getMessage(String id, Object[] objs, Locale locale)
	{
		ClassLoader cl = Thread.currentThread().getContextClassLoader();
		if (cl == null)
		{
			cl = getClass().getClassLoader();
		}

		for (int i = 0; i < resourceEntries.size(); i++)
		{
			MessageResourceEntry resourceEntry = (MessageResourceEntry)resourceEntries.get(i);
			String baseName = resourceEntry.getBaseName();
			String className = resourceEntry.getClassName();
			Class cls = null;
			try
			{
				cls = cl.loadClass(className);
			}
			catch (Exception e)
			{
				Logger log = Logger.getLogger("jp.morpho");
				log.log(Level.WARNING, e.getMessage(), e);
				continue;
			}

			Method method = null;
			try
			{
				method =
					cls.getMethod(
						"getBundle",
						new Class[]
							{ String.class, Locale.class, ClassLoader.class });
			}
			catch (Exception e)
			{
				Logger log = Logger.getLogger("jp.morpho");
				log.log(Level.WARNING, e.getMessage(), e);
				continue;
			}

			ResourceBundle rb = null;
			try
			{
				rb =
					(ResourceBundle) method.invoke(
						cls,
						new Object[] { baseName, locale, cl });
			}
			catch (Exception e)
			{
				Logger log = Logger.getLogger("jp.morpho");
				log.log(Level.WARNING, e.getMessage(), e);
				continue;
			}

			try
			{
				String msg = rb.getString(id);
				if (objs == null)
				{
					return msg;
				}

				try
				{
					MessageFormat mf = new MessageFormat(msg);
					return mf.format(objs);
				}
				catch (Exception e)
				{
					Logger log = Logger.getLogger("jp.morpho");
					log.log(Level.WARNING, e.getMessage(), e);
					continue;
				}
			}
			catch (Exception e)
			{
				continue;
			}
		}
		Logger log = Logger.getLogger("jp.morpho");
		log.warning("Can't find resource for key=" + id);
		return "";
	}

	public synchronized String getFieldName(String id, Locale locale)
	{
		return getMessage(fieldNameBaseKey + id, null, locale);
	}

	public final String getPluginKey()
	{
		return PluginKeys.messageResourceManager;
	}

	public void setPluginContext(PluginContext fc)
		throws PluginException
	{
	}

	public void pluginActivate()
		throws PluginException
	{
	}

	public void pluginRemove()
		throws PluginException
	{
	}

}
