/* Copyright 2000 by Basil Vandegriend.  All rights reserved. */

package com.basilv.core;

import java.net.URL;
import java.util.MissingResourceException;

import javax.swing.ImageIcon;

/**
 * Retrieves resources from resource files that are on the classpath.
 */
public class ResourceRetriever
{

	/**
	 * Load and return the image corresponding to the package the specified class resides in plus 
	 * the image file name suffix.
	 * @param clazz  Cannot be null.
	 * @param imageFileNameSuffix  Cannot be null or empty. Should NOT start with '/'.
	 * @return the image.
	 */
	public static <T> ImageIcon getImage(Class<T> clazz, String imageFileNameSuffix) {
		Assert.notNull("clazz", clazz);
		Assert.notNullOrEmpty("imageFileNameSuffix", imageFileNameSuffix);
		String packageName = clazz.getPackage().getName().replace('.', '/');
		String imageName = packageName + "/" + imageFileNameSuffix;
		return getImage(imageName);		
	}
	
	/**
	 * Load and return the image corresponding to the specified name. The name
	 * must correspond to a file on the classpath, with '/' used as a separator
	 * for package names.
	 * 
	 * @param imageName  Can not be null.
	 */
	public static ImageIcon getImage(String imageName) {
		Assert.notNull("imageName", imageName);

		ClassLoader classLoader = Thread.currentThread().getContextClassLoader();

		// Below code doesn't work with applets (security exception)
		// or in situations where the class loader has been overridden.
		// ClassLoader classLoader = ClassLoader.getSystemClassLoader();

		URL imageUrl = classLoader.getResource(imageName);
		if (imageUrl == null) {
			// Resource not found - throw an exception
			throw new MissingResourceException("Image [" + imageName + "] not found.", ResourceRetriever.class.getName(), imageName);
		}

		ImageIcon image = new ImageIcon(imageUrl);
		return image;
	}

} // class ResourceRetriever
