/*******************************************************************************
* Copyright (c) 2006 IONA Technologies PLC
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
* 
* Contributors:
*     IONA Technologies PLC - initial API and implementation
*******************************************************************************/
package org.eclipse.stp.sc.common;


import java.net.MalformedURLException;
import java.net.URL;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
import java.util.StringTokenizer;
import org.eclipse.jface.resource.ImageDescriptor;
import org.osgi.framework.Bundle;



/**
 * Class to handle accessing Resources
 */
public class CommonResources {
    private static final String BUNDLE_KEY = "org.eclipse.stp.sc.common.CommonResources";
    private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle.getBundle(BUNDLE_KEY);
    private static final String IMAGE_FOLDER_RELATIVE_PATH = "icons/full/";

    protected CommonResources() {
        // this is a base utility class, no public constructor allowed
    }

    /**
     * @return The Celtix plug-in's resource bundle
     */
    public static ResourceBundle getResourceBundle() {
        return RESOURCE_BUNDLE;
    }

    /**
     * @return The Celtix plug-in's bundle
     */
    public static Bundle getBundle() {
        return CommonPlugin.getDefault().getBundle();
    }

    /**
     * Returns the string from the plugin's resource bundle, or 'key' if not
     * found.
     */
    public static String getString(String key) {
        return getString(getResourceBundle(), key);
    }

    /**
     * Returns the string from the specified resource bundle, or 'key' if not
     * found.
     */
    public static final String getString(ResourceBundle bundle, String key) {
        try {
            // if no bundle specified, use global CeltixResources
            return (bundle != null) ? bundle.getString(key)
                                    : getString(getResourceBundle(), key);
        } catch (MissingResourceException e) {
            // before giving up, make sure to try CeltixResources
            if ((bundle != null) && (bundle != getResourceBundle())) {
                return getString(getResourceBundle(), key);
            }

            return key;
        }
    }

    /**
     * Returns the string array from the plugin's resource bundle
     */
    public static String[] getStringArray(String key) {
        return getStringArray(getResourceBundle(), key);
    }

    /**
     * Returns the string array from the specified resource bundle
     */
    public static final String[] getStringArray(ResourceBundle bundle,
        String key) {
        Collection<String> values = new ArrayList<String>();
        String value = getString(bundle, key);

        if ((value != null) && !value.equals("") && !value.equals(key)) {
            StringTokenizer tokenizer = new StringTokenizer(value, ",");

            while (tokenizer.hasMoreTokens()) {
                String token = tokenizer.nextToken();

                if ((token != null) && !token.equals("")) {
                    values.add(token);
                }
            }
        }

        return (String[])values.toArray(new String[0]);
    }

    /**
     * Uses MessageFormat to build string.
     *
     * @param strKey The bundle key of MessageFormat string
     * @param strConcatValues a comma separated list of values to concatenate in the order
     * as specified by the messafe format string
     * @param fValuesIsKey if true then strConcatValues is a ResourceBundle key, else
     * strConcatValues is the actual concatenation string
     *
     * @return The translated string
     */
    public static String getFromMsgFormat(String strKey, String strConcatValues, boolean fValuesIsKey) {
        return getFromMsgFormat(getResourceBundle(), strKey, strConcatValues,
            fValuesIsKey);
    }

    /**
     * Uses MessageFormat to build string.
     *
     * @param bundle The resource bundle to search
     * @param strKey The bundle key of MessageFormat string
     * @param strConcatValues a comma separated list of values to concatenate in the order
     * as specified by the messafe format string
     * @param fValuesIsKey if true then strConcatValues is a ResourceBundle key, else
     * strConcatValues is the actual concatenation string
     *
     * @return The translated string
     */
    public static final String getFromMsgFormat(ResourceBundle bundle,
        String strKey, String strConcatValues, boolean fValuesIsKey) {
        String strMsg = getString(bundle, strKey);

        String strConcat = null;

        if (fValuesIsKey) {
            strConcat = getString(bundle, strConcatValues);
        } else {
            strConcat = strConcatValues;
        }

        Object[] aObj = null;

        if (null != strConcat) {
            StringTokenizer st = new StringTokenizer(strConcat, ",");
            aObj = new Object[st.countTokens()];

            int x = -1;

            while (st.hasMoreTokens()) {
                aObj[++x] = st.nextToken();
            }
        }

        if ((null != aObj) && (aObj.length > 0)) {
            return MessageFormat.format(strMsg, aObj);
        }

        return strMsg;
    } // end getFromMsgFormat()

    /**
     * retrieve an image based on its name (from the plug-in standard image folder)
     * @param imageName
     * @return <code>ImageDescriptor</code> of the image if found or the standard missing image descvritor
     */
    public static ImageDescriptor getImageDescriptor(String imageName) {
        return getImageDescriptor(getBundle(), imageName);
    }

    /**
     * retrieve an image based on its name (from the plug-in standard image folder)
     * @param imageName
     * @return <code>ImageDescriptor</code> of the image if found or the standard missing image descriptor
     */
    public static final ImageDescriptor getImageDescriptor(Bundle bundle,
        String imageName) {
        URL url = getImageUrl(bundle, imageName);

        return (url != null) ? ImageDescriptor.createFromURL(url)
                             : ImageDescriptor.getMissingImageDescriptor();
    }

    /**
     * retrieve the URL of an image file based on its name (from the plug-in standard image folder)
     * @param imageName
     * @return <code>URL</code> of the image if found or null if not found
     */
    public static URL getImageUrl(String imageName) {
        return getImageUrl(getBundle(), imageName);
    }

    public static final URL getImageUrl(Bundle bundle, String imageName) {
        if (bundle == null) {
            bundle = CommonPlugin.getDefault().getBundle();
        }

        try {
            URL baseURL = bundle.getEntry("/");

            return new URL(baseURL, IMAGE_FOLDER_RELATIVE_PATH + imageName);
        } catch (MalformedURLException e) {
            //            LOG.warn("image URL invalid (image probably missing)", e);
            return null;
        }
    }
}
