package org.jcon.ui;

import org.jcon.util.GenLib;
import java.awt.*;
import java.io.InputStream;

import javax.swing.Icon;
import javax.swing.ImageIcon;

/**
 * General Image related methods, all static.
 *
 * @author Jack Harich
 */
public class ImageLib {

private static final Label component = new Label("Dummy");
private static final String defaultClassName =
    "org.jcon.ui.image.ImageMarker";

//---------- Public Methods ------------------------------
/**
 * Returns a loaded Image that is a class resource of
 * instance named resourceName. Returns
 * null if not found or exception.
 */
public static Image loadClassResourceImage(Object instance,
        String resourceName) {

    return loadClassResourceImage(
        instance.getClass().getName(), resourceName);
}
/**
 * Returns a loaded Image that is a class resource of
 * className named resourceName. Returns
 * null if not found or exception.
 * <p>
 * If the className is null then the default is
 * used, which is "org.jcon.ui.image.ImageMarker".
 */
public static Image loadClassResourceImage(String className,
        String resourceName) {

    if (className == null) className = defaultClassName;
try {
    // Get the image
    InputStream resource = Class.forName(className)
        .getResourceAsStream(resourceName);
    byte[] bytes = new byte[resource.available()];
    resource.read(bytes);
    Image image = Toolkit.getDefaultToolkit()
        .createImage(bytes);
    // Load it
    MediaTracker tracker = new MediaTracker(component);
    tracker.addImage(image, 0);
    tracker.waitForID(0); // A poorly named method

    return image;

} catch(Exception ex) {
    GenLib.exception("ImageLib.loadClassResourceImage()",
        "Cannot load '" + resourceName + "' for class '" +
        className + "'.", ex);
    return null;
}

}
/*
* Returns the requested icon in a similar manner to
* loadClassResourceImage().
*/
public static Icon loadClassResourceIcon(String className,
        String resourceName) {

    Image image = loadClassResourceImage(
        className, resourceName); 
    return new ImageIcon(image);
}
//---------- Private Methods -----------------------------
//--- Std
private static void print(String text) {
    System.out.println(text);
}

} // End class
