import java.awt.Image;
import java.awt.MediaTracker;
import java.awt.Toolkit;
import java.awt.Component;
import javax.swing.ImageIcon;
import java.net.URL;


/**
 * Encapsulates image loading so clients can open an image simply without
 * resorting to MediaTrackers or Icons. In the current version of this class the
 * getImage(..) functions use the swing ImageIcon class which uses a
 * MediaTracker internally. This means the MediaTracker code doesn't appear here
 * (but does in ImageIcon).
 * <P>
 * These factory methods support getting an image by filename, by url, and from
 * an Applet/jar file using the Component/name factory method.
 * 
 * @author Owen Astrachan
 */
public class ImageFactory
{
    /**
     * load an image from a file, return the image waits for image to be loaded
     * before returning
     * 
     * @param filename is the source of the image (e.g., foo.gif)
     * @return the image bound to filename
     */
    public static Image getImage (String filename)
    {
        return getImage(new ImageIcon(filename));
    }

    /**
     * load an image from a URL, return the image waits for image to be loaded
     * before returning
     * 
     * @param filename is the source of the image (e.g., foo.gif)
     * @return the image bound to filename
     */
    public static Image getImage (URL urlname)
    {
        return getImage(new ImageIcon(urlname));
    }

    /**
     * Load an image from a jar file, e.g., using the Component's getResource
     * method. Used, for example, by an Applet passing itself as the Component
     * and the name of the file in the jar file storing the image.
     * 
     * @param comp is the Applet/JApplet/Component
     * @param name is the jar file resource storing the image
     * @return the image
     */
    public static Image getImage (Component comp, String name)
    {
        return getImage(comp.getClass().getResource(name));
    }

    /**
     * Returns an image repesentation of the given icon.
     */
    private static Image getImage (ImageIcon icon)
    {
        return icon.getImage().getScaledInstance(PuzzleConsts.IMAGE_SIZE,
                                                 PuzzleConsts.IMAGE_SIZE,
                                                 Image.SCALE_REPLICATE);
    }
}
