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.ChipSet;
import rpgEngine.Util.ImageManip;

public class ChipSetPool {
	private static ChipSetPool instance;
	private Dictionary<Integer,ChipSet> items;
	
	private ChipSetPool() {
		items = new Hashtable<Integer,ChipSet>();
		loadData();
	}
	
	
	public static ChipSetPool getInstance() {
		if(instance == null) {
			instance = new ChipSetPool();
		}
		
		return instance;
	}
	
	
	public ChipSet getPoolItem(Integer i) {
		ChipSet item = null;
		
		try 
		{
			item = items.get(i);	
		}
		catch(Exception e) 
		{
			return null;	
		}
		
		return item;
	}
	
	
	private void loadData() {
		String filename = "chipsets.cfg";
		String[] columns = null;
		InputStream fileStream = null;
		InputStream imageStream = null;
		BufferedReader reader = null;
		String line = "";
		BufferedImage baseImg = null;
		BufferedImage img = null;
		ChipSet chipset = null;
		
		//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);
					
					img = baseImg.getSubimage(Integer.parseInt(columns[3]), 
											  Integer.parseInt(columns[4]), 
											  Integer.parseInt(columns[5]), 
											  Integer.parseInt(columns[6]));
					
					if(columns[7].equals("-1") == false) {
						img = ImageManip.makeColorTransparent(img,Integer.parseInt(columns[7]),
													   Integer.parseInt(columns[8]),
													   Integer.parseInt(columns[9]));
					}
					
					chipset = new ChipSet(img,columns[1]);
					
					items.put(Integer.parseInt(columns[0]),chipset);
				}
			}
		}
		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;
		}
	}

	
	
}
