package org.argosdic.resource;

import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Enumeration;
import java.util.MissingResourceException;
import java.util.ResourceBundle;

import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.jface.resource.ImageRegistry;
import org.eclipse.jface.util.Assert;

/**
 * ResourceManager.java
 * @author Xavier Cho
 * @version $Revision: 1.3 $ $Date: 2005/03/13 09:10:16 $
 */
public class ResourceManager {
    public static final String RESOURCE_BUNDLE = "org.argosdic.resource.ApplicationResources"; //$NON-NLS-1$
    public static final String ACTION_PREFIX = "org.argosdic.action"; //$NON-NLS-1$

    private static ResourceManager instance;
    private ImageRegistry imageRegistry;
    private ResourceBundle bundle;

    private ResourceManager() {
        this.bundle = ResourceBundle.getBundle(RESOURCE_BUNDLE);
        this.imageRegistry = new ImageRegistry();
    }

    public static ResourceManager getInstance() {
        if (instance == null) {
            synchronized (ResourceManager.class) {
                instance = new ResourceManager();
            }
        }
        return instance;
    }

    public String getString(String key) {
        Assert.isNotNull(key);

        String value = null;

        try {
            value = bundle.getString(key);
        } catch (MissingResourceException e) {
        }

        return value;
    }

    public String getString(String key, Object[] args) {
        Assert.isNotNull(key);

        String value = null;

        try {
            value = bundle.getString(key);
            value = MessageFormat.format(value, args);
        } catch (MissingResourceException e) {
        }

        return value;
    }

    public ImageDescriptor getImage(String key) {
        ImageDescriptor image = imageRegistry.getDescriptor(key);

        if (image == null) {
            String path = getString(key);

            if (path != null) {
                image =
                    ImageDescriptor.createFromFile(ResourceManager.class, path);
                imageRegistry.put(key, image);
            }
        }

        return image;
    }

    public Collection getActionNames() {
        Collection actions = new ArrayList(20);

        Enumeration e = bundle.getKeys();
        while (e.hasMoreElements()) {
            String name = (String) e.nextElement();

            if (name.startsWith(ACTION_PREFIX)) {
                int index = name.lastIndexOf("Action") + 6; //$NON-NLS-1$
                name = name.substring(0, index);

                if (!actions.contains(name)) {
                    actions.add(name);
                }
            }
        }

        return actions;
    }
}