/*
 * $Id: MessageResources.java 471754 2006-11-06 14:55:09Z husted $
 *
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you 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 org.apache.struts.util;

import java.io.Serializable;
import java.text.MessageFormat;
import java.util.Locale;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;



/**
 * General purpose abstract class that describes an API for retrieving
 * Locale-sensitive messages from underlying resource locations of an
 * unspecified design, and optionally utilizing the <code>MessageFormat</code>
 * class to produce internationalized messages with parametric replacement.
 * <p> Calls to <code>getMessage()</code> variants without a
 * <code>Locale</code> argument are presumed to be requesting a message string
 * in the default <code>Locale</code> for this JVM. <p> Calls to
 * <code>getMessage()</code> with an unknown key, or an unknown
 * <code>Locale</code> will return <code>null</code> if the
 * <code>returnNull</code> property is set to <code>true</code>.  Otherwise, a
 * suitable error message will be returned instead. <p> <strong>IMPLEMENTATION
 * NOTE</strong> - Classes that extend this class must be Serializable so that
 * instances may be used in distributable application server environments.
 *
 * @version $Rev: 471754 $ $Date: 2005-08-29 23:57:50 -0400 (Mon, 29 Aug 2005)
 *          $
 */
public abstract class MessageResources implements Serializable {

    // ------------------------------------------------------------- Properties

    /** serialVersionUID */
    private static final long serialVersionUID = -3823833250965010653L;

    /**
     * Commons Logging instance.
     */
    private static final Log LOG = LogFactory.getLog(MessageResources.class);

    // --------------------------------------------------------- Static Methods

    /**
     * The configuration parameter used to initialize this MessageResources.
     */
    private final String config;

    /**
     * The default Locale for our environment.
     */
    private final Locale defaultLocale = Locale.getDefault();

    /**
     * The set of previously created MessageFormat objects, keyed by the key
     * computed in <code>messageKey()</code>.
     */
    private final ConcurrentMap<String, MessageFormat> formats = new ConcurrentHashMap<>();

    /**
     * Indicate is a <code>null</code> is returned instead of an error message
     * string when an unknown Locale or key is requested.
     */
    private final boolean returnNull;

    /**
     * Indicates whether 'escape processing' should be performed on the error
     * message string.
     */
    private final boolean escape;

    // ----------------------------------------------------------- Constructors

    /**
     * Construct a new MessageResources according to the specified
     * parameters.
     *
     * @param cfg The configuration parameter for this MessageResources
     */
    public MessageResources(final String cfg) {
        this(cfg, false, true);
    }

    /**
     * Construct a new MessageResources according to the specified
     * parameters.
     *
     * @param cfg The configuration parameter for this MessageResources
     * @param nullReturn The returnNull property we should initialize with
     */
    public MessageResources(final String cfg, final boolean nullReturn) {
        this(cfg, nullReturn, true);
    }

    /**
     * Construct a new MessageResources according to the specified
     * parameters.
     *
     * @param cfg The configuration parameter for this MessageResources
     * @param nullReturn The returnNull property we should initialize with
     * @param esc escape processing
     */
    public MessageResources(final String cfg, final boolean nullReturn, final boolean esc) {
        this.config = cfg;
        this.returnNull = nullReturn;
        this.escape = esc;
    }

    /**
     * The configuration parameter used to initialize this MessageResources.
     *
     * @return parameter used to initialize this MessageResources
     */
    public String getConfig() {
        return this.config;
    }

    /**
     *
     * @return DefaultLocale
     */
    public Locale getDefaultLocale() {
        return this.defaultLocale;
    }

    /**
     * Indicates that a <code>null</code> is returned instead of an error
     * message string if an unknown Locale or key is requested.
     *
     * @return true if null is returned if unknown key or locale is requested
     */
    public boolean getReturnNull() {
        return this.returnNull;
    }

    /**
     * Indicates whether 'escape processing' should be performed on the error
     * message string.
     * @return boolean
     * @since Struts 1.2.8
     */
    public boolean isEscape() {
        return this.escape;
    }

    // --------------------------------------------------------- Public Methods

    /**
     * Returns a text message for the specified key, for the default Locale.
     * @param key The message key to look up
     * @return Message
     */
    public String getMessage(final String key) {
        return getMessage(null, key);
    }

    /**
     * Returns a text message after parametric replacement of the specified
     * parameter placeholders.
     * @param key  The message key to look up
     * @param args An array of replacement parameters for placeholders
     * @return Message
     */
    public String getMessage(final String key, final Object... args) {
        return getMessage(null, key, args);
    }

    /**
     * Returns a text message for the specified key, for the default Locale. A
     * null string result will be returned by this method if no relevant
     * message resource is found for this key or Locale, if the
     * <code>returnNull</code> property is set.  Otherwise, an appropriate
     * error message will be returned. <p> This method must be implemented by
     * a concrete subclass.
     * @param locale The requested message Locale, or <code>null</code> for
     *               the system default Locale
     * @param key    The message key to look up
     * @return Message
     */
    public abstract String getMessage(Locale locale, String key);

    /**
     * Returns a text message after parametric replacement of the specified
     * parameter placeholders.  A null string result will be returned by this
     * method if no resource bundle has been configured.
     * @param locale The requested message Locale, or <code>null</code> for
     *               the system default Locale
     * @param key    The message key to look up
     * @param args   An array of replacement parameters for placeholders
     * @return Message
     */
    public String getMessage(final Locale locale, final String key, final Object... args) {
        // Cache MessageFormat instances as they are accessed
        Locale lcl = locale;
        if (lcl == null) {
            lcl = this.defaultLocale;
        }

        String formatKey = messageKey(lcl, key);

        MessageFormat format = this.formats.get(formatKey);

        if (format == null) {
            String formatString = getMessage(lcl, key);

            if (formatString == null) {
                return this.returnNull ? null : ("???" + formatKey + "???");
            }

            format = new MessageFormat(escape(formatString));
            format.setLocale(lcl);
            MessageFormat mf = this.formats.putIfAbsent(formatKey, format);
            if (mf != null) {
                format = mf;
            }
        }
        return format.format(args);
    }

    /**
     * Return <code>true</code> if there is a defined message for the
     * specified key in the system default locale.
     * @param key The message key to look up
     * @return boolean
     */
    public boolean isPresent(final String key) {
        return this.isPresent(null, key);
    }

    /**
     * Return <code>true</code> if there is a defined message for the
     * specified key in the specified Locale.
     * @param locale The requested message Locale, or <code>null</code> for
     *               the system default Locale
     * @param key    The message key to look up
     * @return boolean
     */
    public boolean isPresent(final Locale locale, final String key) {
        String message = getMessage(locale, key);
        return message != null && (!message.startsWith("???") || !message.endsWith("???"));
    }

    // ------------------------------------------------------ Protected Methods

    /**
     * Escape any single quote characters that are included in the specified
     * message string.
     * @param string The string to be escaped
     * @return String
     */
    protected String escape(final String string) {
        if (!isEscape()) {
            return string;
        }

        if ((string == null) || (string.indexOf('\'') < 0)) {
            return string;
        }

        int n = string.length();
        StringBuilder sb = new StringBuilder(n);

        for (int i = 0; i < n; i++) {
            char ch = string.charAt(i);

            if (ch == '\'') {
                sb.append('\'');
            }

            sb.append(ch);
        }

        return sb.toString();
    }

    /**
     * Compute and return a key to be used in caching information by a Locale.
     * <strong>NOTE</strong> - The locale key for the default Locale in our
     * environment is a zero length String.
     * @param locale The locale for which a key is desired
     * @return localeKey
     */
    protected String localeKey(final Locale locale) {
        return (locale == null) ? "" : locale.toString();
    }

    /**
     * Compute and return a key to be used in caching information by Locale
     * and message key.
     * @param locale The Locale for which this format key is calculated
     * @param key    The message key for which this format key is calculated
     * @return messageKey
     */
    protected String messageKey(final Locale locale, final String key) {
        return localeKey(locale) + "." + key;
    }

    /**
     * Compute and return a key to be used in caching information by locale
     * key and message key.
     * @param localeKey The locale key for which this cache key is calculated
     * @param key       The message key for which this cache key is
     *                  calculated
     * @return messageKey
     */
    protected String messageKey(final String localeKey, final String key) {
        return localeKey + "." + key;
    }

    /**
     * Log a message to the Writer that has been configured for our use.
     *
     * @param message The message to be logged
     */
    public void log(final String message) {
        LOG.debug(message);
    }

    /**
     * Log a message and exception to the Writer that has been configured for
     * our use.
     *
     * @param message   The message to be logged
     * @param throwable The exception to be logged
     */
    public void log(final String message, final Throwable throwable) {
        LOG.debug(message, throwable);
    }
}
