/*
 * The contents of this file are subject to the terms 
 * of the Common Development and Distribution License 
 * (the License).  You may not use this file except in
 * compliance with the License.
 * 
 * You can obtain a copy of the license at 
 * https://glassfish.dev.java.net/public/CDDLv1.0.html or
 * glassfish/bootstrap/legal/CDDLv1.0.txt.
 * See the License for the specific language governing 
 * permissions and limitations under the License.
 * 
 * When distributing Covered Code, include this CDDL 
 * Header Notice in each file and include the License file 
 * at glassfish/bootstrap/legal/CDDLv1.0.txt.  
 * If applicable, add the following below the CDDL Header, 
 * with the fields enclosed by brackets [] replaced by
 * you own identifying information: 
 * "Portions Copyrighted [year] [name of copyright owner]"
 * 
 * Copyright 2006 Sun Microsystems, Inc. All rights reserved.
 */

/*
 * @(#) StringManagerBase.java
 *
 * Copyright 2000-2001 by iPlanet/Sun Microsystems, Inc.,
 * 901 San Antonio Road, Palo Alto, California, 94303, U.S.A.
 * All rights reserved.
 *
 * This software is the confidential and proprietary information
 * of iPlanet/Sun Microsystems, Inc. ("Confidential Information").
 * You shall not disclose such Confidential Information and shall
 * use it only in accordance with the terms of the license
 * agreement you entered into with iPlanet/Sun Microsystems.
 */
package com.sun.enterprise.util.i18n;

import java.util.ResourceBundle;
import java.util.Locale;
import java.util.Hashtable;
import java.text.MessageFormat;

import java.util.logging.Level;
import java.util.logging.Logger;
import com.sun.logging.LogDomains;

/**
 * Implementation of a local string manager. Provides access to i18n messages
 * for classes that need them.
 *
 * <p> One StringManagerBase per resource bundle name can be created and accessed by the 
 * getManager method call. 
 *
 * <xmp>
 * Example:
 *
 * [LocalStrings.properties]
 * test=At {1,time} on {1,date}, there was {2} on planet {0,number,integer}
 *
 *
 *  StringManagerBase sm  = StringManagerBase.getStringManager("LocalStrings.properties");
 *  .....
 *
 *
 *  try {
 *      ....
 *  } catch (Exception e) {
 *      String localizedMsg = sm.getString("test", 
 *          new Integer(7), new java.util.Date(System.currentTimeMillis()), 
 *          "a disturbance in the Force");
 *
 *      throw new MyException(localizedMsg, e);
 *  }
 *
 * Localized message:
 *   At 2:27:41 PM on Jul 8, 2002, there was a disturbance in the Force
 *   on planet 7
 *
 * </xmp>
 *
 * @author  Nazrul Islam
 * @since   JDK1.4
 */
public class StringManagerBase {

    /** logger used for this class */
    private static Logger _logger=LogDomains.getLogger(LogDomains.UTIL_LOGGER);

    /** resource bundle to be used by this manager */
    private ResourceBundle _resourceBundle  = null;
    
    /** default value used for undefined local string */
    private static final String NO_DEFAULT = "No local string defined";

    /** cache for all the local string managers (per pkg) */
    private static Hashtable managers = new Hashtable();

    /**
     * Initializes the resource bundle.
     *
     * @param    resourceBundleName    name of the resource bundle
     */    
    protected StringManagerBase(String resourceBundleName) {
        try {            
            _resourceBundle = ResourceBundle.getBundle(resourceBundleName);
        } catch (Exception e) {
            _logger.log(Level.SEVERE, "iplanet_util.no_resource_bundle", e);
        }
    }

    /**
     * Returns a local string manager for the given resourceBundle name.
     *
     * @param    resourceBundleName    name of the resource bundle
     *
     * @return   a local string manager for the given package name
     */
    public synchronized static StringManagerBase getStringManager(String resourceBundleName) {
        StringManagerBase mgr = (StringManagerBase) managers.get(resourceBundleName);
        if (mgr == null) {
            mgr = new StringManagerBase(resourceBundleName);
            try {
                managers.put(resourceBundleName, mgr);
            } catch (Exception e) {
                _logger.log(Level.SEVERE,"iplanet_util.error_while_caching",e);
            }
        }
        return mgr;
    }

    /**
     * Returns a localized string.
     *
     * @param    key           the name of the resource to fetch
     *
     * @return   the localized string
     */
    public String getString(String key) {
        return getStringWithDefault(key, NO_DEFAULT);
    }

    /**
     * Returns a localized string. If the key is not found, it will
     * return the default given value.
     *
     * @param    key           the name of the resource to fetch
     * @param    defaultValue  the default return value if not found
     *
     * @return   the localized string
     */
    public String getStringWithDefault(String key, String defaultValue) {

        String value = null;

        try {
            value = this._resourceBundle.getString(key);
        } catch (Exception e) {
            _logger.log(Level.FINE,"No local string for: " + key, e);
        }

        if (value != null) {
            return value;
        } else {
            return defaultValue;
        }
    }

    /**
     * Returns a local string for the caller and format the arguments 
     * accordingly. If the key is not found, it will use the given 
     * default format.
     *
     * @param   key            the key to the local format string
     * @param   defaultFormat  the default format if not found in the resources
     * @param   arguments      the set of arguments to provide to the formatter
     *
     * @return  a formatted localized string
     */
    public String getStringWithDefault(String key, String defaultFormat, 
            Object arguments[]) {

        MessageFormat f =
            new MessageFormat( getStringWithDefault(key, defaultFormat) );

        for (int i=0; i<arguments.length; i++) {

            if ( arguments[i] == null ) {

                arguments[i] = "null";

            } else if  ( !(arguments[i] instanceof String) &&
                     !(arguments[i] instanceof Number) &&
                     !(arguments[i] instanceof java.util.Date)) {

                arguments[i] = arguments[i].toString();
            }
        }

        String fmtStr = null; 
        try {
            fmtStr =  f.format(arguments);
        } catch (Exception e) {
            _logger.log(Level.WARNING, "iplanet_util.error_while_formating", e);

            // returns default format
            fmtStr = defaultFormat;
        }
        return fmtStr;
    }

    /**
     * Returns a local string for the caller and format the arguments
     * accordingly.
     *
     * @param   key     the key to the local format string
     * @param   arg1    the one argument to be provided to the formatter
     *
     * @return  a formatted localized string
     */
    public String getString(String key, Object arg1) {

        return getStringWithDefault(key, NO_DEFAULT, new Object[] {arg1});
    }

    /**
     * Returns a local string for the caller and format the arguments
     * accordingly.
     *
     * @param   key     the key to the local format string
     * @param   arg1    first argument to be provided to the formatter
     * @param   arg2    second argument to be provided to the formatter
     *
     * @return  a formatted localized string
     */
    public String getString(String key, Object arg1, Object arg2) {

        return getStringWithDefault(key, NO_DEFAULT, new Object[] {arg1, arg2});
    }

    /**
     * Returns a local string for the caller and format the arguments
     * accordingly.
     *
     * @param   key     the key to the local format string
     * @param   arg1    first argument to be provided to the formatter
     * @param   arg2    second argument to be provided to the formatter
     * @param   arg3    third argument to be provided to the formatter
     *
     * @return  a formatted localized string
     */
    public String getString(String key, Object arg1, Object arg2,
            Object arg3) {

        return getStringWithDefault(key, NO_DEFAULT,
                                    new Object[] {arg1, arg2, arg3});
    }

    /**
     * Returns a local string for the caller and format the arguments
     * accordingly.
     *
     * @param   key     the key to the local format string
     * @param   arg1    first argument to be provided to the formatter
     * @param   arg2    second argument to be provided to the formatter
     * @param   arg3    third argument to be provided to the formatter
     * @param   arg4    fourth argument to be provided to the formatter
     *
     * @return  a formatted localized string
     */
    public String getString(String key, Object arg1, Object arg2, 
            Object arg3, Object arg4) {

        return getStringWithDefault(key, NO_DEFAULT, 
                                    new Object[] {arg1, arg2, arg3, arg4});
    }

    /**
     * Returns a local string for the caller and format the arguments
     * accordingly.
     *
     * @param   key     the key to the local format string
     * @param   args    the array of arguments to be provided to the formatter
     *
     * @return  a formatted localized string
     */
    public String getString(String key, Object[] args) {

        return getStringWithDefault(key, NO_DEFAULT, args);
    }


    /**
     * Unit test code.
     *
     * @param    args    arguments from command line
     */
    public static void main(String[] args) {

        long b = System.currentTimeMillis();
        try {
            StringManagerBase sm = 
                StringManagerBase.getStringManager("com.sun.enterprise.util.i18n.LocalStrings");

            String ls = sm.getString("test", Integer.valueOf(7),
                         new java.util.Date(System.currentTimeMillis()),
                         "a disturbance in the Force");

            System.out.println(ls);

            System.out.println( sm.getString("bad") );

        } catch (Exception e) {
            System.out.println("---- Error ---- ");
            e.printStackTrace();
        } finally {
            long a = System.currentTimeMillis();
            System.out.println("Time: " + (a-b) );
        }
    }
}
