package ui.view;

import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;

import javax.imageio.ImageIO;

public class Util {
	/**
	 * 30x30 pixel FileNotFound Icon, which can be shown without using I/O operations
	 */
	static private Image defaultImage = createDefaultImage();
	
	/**
	 * creates the default Image 
	 * @return 30x30 Image, showing a red cross
	 */
	private static Image createDefaultImage() {
		BufferedImage def = new BufferedImage(30,30,BufferedImage.TYPE_BYTE_INDEXED);
		for(int x = 0; x < 30; x++)
			for(int y = 0; y < 30; y++){
				if(x == 29 || y == 29)
					//Border Bottom/Left -> Light Grey
					def.setRGB(x, y, 13158600);
				else if(x == 0 || y == 0)
					//Border Top/Right -> Dark Grey
					def.setRGB(x, y, 6316128);
				else if((x == y || x == 31 - y) && 6 < x && x < 25)
					//Red Cross in the middle
					def.setRGB(x, y, 13107200);
				else //all other Pixels are white
					def.setRGB(x, y, 16777215);
				
			}
		return def;
	}
	
	static Image loadImage(Object origin, String url, int w, int h, int scale){
		return loadImage(origin,url).getScaledInstance(w, h, scale);
	}
	
	static Image loadImage(Object origin, String url, int w, int h){
		return loadImage(origin,url,w,h, Image.SCALE_SMOOTH);
	}
	
	static Image loadImage(Object origin, String url){
		try {
			return ImageIO.read(loadStream(origin, url));
		} catch (IOException e) {
			System.err.println("Warning: '" + url + "' loading failed!");
			e.printStackTrace();
			return defaultImage;
		}
	}
	
	static InputStream loadStream(Object origin, String url){

		InputStream o=origin.getClass().getResourceAsStream(url);
		if(o!=null)return o;
		else{
			System.out.println("Loading of resource \""+url+"\" as stream failed.\nWill attempt to load as File.");
			boolean rootSymbol=false;	//Whether url starts with a / or \
			switch(url.charAt(0)){		//So we can make sure to consttruct res/path correctly.
			case '/':case '\\':rootSymbol=true;
			}
			try {
				return new FileInputStream("res"+(rootSymbol?"":"/")+url);
			} catch (FileNotFoundException e1) {
				e1.printStackTrace();
			}
			return null;
		}
	}
}