package rpgEngine.Resources;

import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Dictionary;
import java.util.Hashtable;
import javax.imageio.ImageIO;
import rpgEngine.Data.Raw.Graphics.EnemySet;

public class EnemySetPool {
	private static EnemySetPool instance;
	private Dictionary<Integer,EnemySet> items;
	
	private EnemySetPool() {
		items = new Hashtable<Integer,EnemySet>();
		loadData();
	}
	
	
	public static EnemySetPool getInstance() {
		if(instance == null) {
			instance = new EnemySetPool();
		}
		
		return instance;
	}
	
	
	public EnemySet getPoolItem(Integer i) {
		EnemySet item = null;
		
		try 
		{
			item = items.get(i);	
		}
		catch(Exception e) 
		{
			return null;	
		}
		
		return item;
	}
	
	
	private void loadData() {
		String filename = "enemyset.cfg";
		String[] columns = null;
		InputStream fileStream = null;
		InputStream imageStream = null;
		BufferedReader reader = null;
		String line = "";
		BufferedImage baseImg = null;
		BufferedImage img = null;
		EnemySet enemySet = null;
		
		Integer oldWidth = 0;
		Integer newWidth = 0;
		Integer oldHeight = 0;
		Integer newHeight = 0;
		Double ratio = 0.0;
		
		
		//Open File
		try {
			fileStream = this.getClass().getResourceAsStream("Config/" + filename);
			reader = new BufferedReader(new InputStreamReader(fileStream));
		}
		catch(Exception e) {
			System.err.println("Error openning file " + filename);
			System.err.println(e.toString());
			return;
		}
		
		//Read File
		try {
			while(reader.ready()) {
				line = reader.readLine();
				
				columns = line.split(",");
				
				if(columns[0].equals("ID") == false) {
					imageStream = this.getClass().getResourceAsStream("Image/" + columns[2]);
					baseImg = ImageIO.read(imageStream);
					
					oldWidth = baseImg.getWidth();
					oldHeight = baseImg.getHeight();
					
					ratio = (double)oldWidth / (double)oldHeight;
					
					if(oldWidth > oldHeight) {
						newWidth = 150;
						newHeight = (int)((double)newWidth / ratio);
					}
					else {
						newHeight = 150;
						newWidth = (int)((double)newHeight * ratio);
					}
					
					img = new BufferedImage(newWidth,newHeight,BufferedImage.TYPE_INT_ARGB);
					img.createGraphics().drawImage(baseImg, 0, 0, newWidth, newHeight, null);
					
					enemySet = new EnemySet(columns[1],img);
					
					items.put(Integer.parseInt(columns[0]),enemySet);
				}
			}
		}
		catch(Exception e) {
			System.err.println("Error reading file " + filename);
			System.err.println(e.toString());
			return;
		}
		
		//Close File
		try {
			reader.close();
			fileStream.close();
		}
		catch(Exception e) {
			System.err.println("Error closing file " + filename);
			System.err.println(e.toString());
			return;
		}
	}
	
}
