package j3deditor.bin.util;

import java.awt.Image;
import java.awt.Toolkit;

import java.io.File;

import java.io.FileNotFoundException;

import java.net.URL;

import javax.swing.ImageIcon;


/**
 * Tool for loading images.
 *
 * @author Risto Seene
 */
public class ImageLoader{

	/** path of the images inside the JAR file. */
	public static final String imagePath = "/j3deditor/images/";


	/**
	 * Creates an instance of <code>ImageLoader</code>.
	 */
	public ImageLoader(){
	}


	/**
	 * Loads an image from JAR file
	 * and returns it as an instance of <code>Image</code>.
	 *
	 * @param path
	 *	the path of an image file relative to "/j3deditor/images"
	 *
	 * @return If file exists returns the image as an instance of
	 *	<code>Image</code>, otherwise returns <code>null</code>
	 */
	public Image getImage(String path){
		Image image = null;

		try{
			URL url = Utilities.class.getResource(imagePath + path);

			if(url == null){
				throw (new java.io.FileNotFoundException(imagePath + path + " (The system cannot find the file specified)"));
			}

			image = Toolkit.getDefaultToolkit().getImage(url);
		} catch(Throwable t){
			Utilities.out.throwWarning(t);
		}

		return image;
	}


	/**
	 * Loads an image from disk
	 * and returns it as an instance of <code>Image</code>.
	 *
	 * @param source
	 *        image file
	 *
	 * @return If file exists returns the image as an instance of
	 *        <code>Image</code>, otherwise returns <code>null</code>
	 */
	public Image getImage(File source){
		Image image = null;

		try{
			if(!source.exists()){
				throw (new FileNotFoundException(source.getPath() + " (The system cannot find the file specified)"));
			}

			String imgPath = source.getCanonicalPath();
			image = Toolkit.getDefaultToolkit().getImage(imgPath);
		} catch(Throwable t){
			Utilities.out.throwWarning(t);
		}

		return image;
	}


	/**
	 * Loads an image from JAR file
	 * and returns it as an instance of <code>ImageIcon</code>.
	 *
	 * @param path
	 *	the path of an image file relative to "/j3deditor/images"
	 *
	 * @return If file exists returns the image as an instance of
	 *	<code>ImageIcon</code>, otherwise returns <code>null</code>
	 */
	public ImageIcon getImageIcon(String path){
		try{
			return new ImageIcon(getImage(path));
		} catch(Throwable t){
			return null;
		}
	}


	/**
	 * Loads an image from disk
	 * and returns it as an instance of <code>ImageIcon</code>.
	 *
	 * @param source
	 *        image file
	 *
	 * @return If file exists returns the image as an instance of
	 *        <code>ImageIcon</code>, otherwise returns <code>null</code>
	 */
	public ImageIcon getImageIcon(File source){
		try{
			return new ImageIcon(getImage(source));
		} catch(Throwable t){
			return null;
		}
	}

}
