package rpgEngine.Resources;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Dictionary;
import java.util.Hashtable;
import rpgEngine.Data.Abstract.Item;


public class ItemPool {
	private static ItemPool instance;
	private Dictionary<Integer,Item> items;
	
	private ItemPool() {
		items = new Hashtable<Integer,Item>();
		loadData();
	}
	
	
	public static ItemPool getInstance() {
		if(instance == null) {
			instance = new ItemPool();
		}
		
		return instance;
	}
	
	
	public Item getPoolItem(Integer i) {
		Item item = null;
		
		try 
		{
			item = items.get(i);	
		}
		catch(Exception e) 
		{
			return null;	
		}
		
		return item;
	}
	
	
	private void loadData() {	
		String filename = "items.cfg";
		String[] columns = null;
		InputStream fileStream = null;
		BufferedReader reader = null;
		String line = "";
		Item item = null;
		Integer type = 0;
		Integer ID = -1;
		
		//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) {
					ID = Integer.valueOf(columns[0]);
					
					if(columns[2].equals("Healing")) {
						type = Item.TYPE_HEALING;
					}
					else if(columns[2].equals("Weapon")) {
						type = Item.TYPE_WEAPON;
					}
					else if(columns[2].equals("Helmet")) {
						type = Item.TYPE_HELMET;	
					}
					else if(columns[2].equals("Armor")) {
						type = Item.TYPE_ARMOR;
					}
					else if(columns[2].equals("Accessory")) {
						type = Item.TYPE_ACCESSORY;
					}
					else if(columns[2].equals("Tome")) {
						type = Item.TYPE_TOME;
					}
					else if(columns[2].equals("Revive")) {
						type = Item.TYPE_REVIVE;
					}
					else if(columns[2].equals("Restore")) {
						type = Item.TYPE_MP_HEALING;
					}
					else {
						type = Item.TYPE_HEALING;
					}
					
					item = new Item(ID, columns[1],columns[11],type,
										Integer.parseInt(columns[10]),
										Integer.parseInt(columns[9]),
										Integer.parseInt(columns[3]),
										Integer.parseInt(columns[4]),
										Integer.parseInt(columns[5]),
										Integer.parseInt(columns[6]),
										Integer.parseInt(columns[7]),
										Integer.parseInt(columns[8])
									);
					
					items.put(Integer.parseInt(columns[0]),item);
				}
			}
		}
		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;
		}
	}

}
