package siuUtil;

import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.MediaTracker;
import java.awt.image.BufferedImage;
import java.net.URL;

import javax.swing.ImageIcon;

public class ImageLoad {
	// Method to load ImageIcons from a file - if the image cannot
	// be loaded correctly it creates an ImageIcon with an error
	// message inside it

	protected static ClassLoader theLoader = null;

	public static void setLoader(ClassLoader loader) {
		theLoader = loader;
	}

	public static ImageIcon createImgIcon(String imgName) {
		ImageIcon imIc = new ImageIcon();
		final int IMG_WID = 100; // set to match desired
		final int IMG_HT = 100; // image width and height
		int loadStat = MediaTracker.ERRORED;
		String errObject = "Image File";
		boolean badLoader = false;
		boolean badURL = false;

		if (theLoader == null) {
			// use something like theLoader = getClass().getClassLoader();
			errObject = new String("Undef Loader");
			badLoader = true;

		} else {
			URL theURL = theLoader.getResource(imgName);
			
			if (theURL == null) {
				badURL = true;
				errObject = new String("Image URL");
			}
			if (!badURL) {
				imIc = new ImageIcon(theURL);
				loadStat = imIc.getImageLoadStatus();
			}
		}
		if (badLoader || badURL || (loadStat != MediaTracker.COMPLETE)) {
			// Create an error icon
			BufferedImage bufImg = new BufferedImage(IMG_WID, IMG_HT,
					BufferedImage.TYPE_INT_RGB);
			Graphics2D g = bufImg.createGraphics();
			g.setColor(Color.WHITE);
			g.fillRect(0, 0, IMG_WID, IMG_HT);
			g.setColor(Color.RED);
			g.drawString(errObject, 0, 20);
			g.setColor(Color.BLACK);
			g.drawString(imgName, 0, 50);
			g.setColor(Color.RED);
			g.drawString("NOT FOUND", 0, 80);
			imIc = new ImageIcon(bufImg);
		}
		return imIc;
	}
}

