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.2 $ $Date: 2003/09/12 10:23:52 $
 */
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 enum = bundle.getKeys();
        while (enum.hasMoreElements()) {
            String name = (String) enum.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;
    }
}