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.Party.HumanPlayer;
import rpgEngine.Data.Raw.Graphics.CharacterSet;

public class HeroPool {
	private static HeroPool instance;
	private Dictionary<Integer,HumanPlayer> items;

	
	private HeroPool() {
		items = new Hashtable<Integer,HumanPlayer>();
		loadData();
	}
	
	
	public static HeroPool getInstance() {
		if(instance == null) {
			instance = new HeroPool();
		}
		
		return instance;
	}
	
	
	public HumanPlayer getPoolItem(Integer i) {
		HumanPlayer item = null;
		
		try 
		{
			item = items.get(i);	
		}
		catch(Exception e) 
		{
			return null;	
		}
		
		return item;
	}
	
	
	public HumanPlayer getCopyOfItem(Integer i) {
		HumanPlayer p = new HumanPlayer();
		HumanPlayer h = HeroPool.getInstance().getPoolItem(i);
		
		p.setHeroID(h.getHeroID());
		p.setAttack(h.getAttack());
		p.setBarrier(h.getBarrier());
		p.setCharSet(h.getCharSet());
		p.setDefense(h.getDefense());
		p.setHP(h.getHP());
		p.setMaxHP(h.getMaxHP());
		p.setMP(h.getMP());
		p.setMaxMP(h.getMaxMP());
		p.setSkill(h.getSkill());
		p.setName(h.getName());
		
		return p;
	}
	
	
	private void loadData() {	
		String filename = "heros.cfg";
		String[] columns = null;
		InputStream fileStream = null;
		BufferedReader reader = null;
		String line = "";
		HumanPlayer hero = null;
		CharacterSet cs = null;
		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]);
					cs = CharacterSetPool.getInstance().getPoolItem(Integer.parseInt(columns[2]));
					
					hero = new HumanPlayer(ID,
										   Integer.parseInt(columns[4]),
										   Integer.parseInt(columns[5]),
										   Integer.parseInt(columns[6]),
										   Integer.parseInt(columns[7]),
										   Integer.parseInt(columns[8]),
										   Integer.parseInt(columns[9]),
										   cs,
										   columns[1],
										   Integer.parseInt(columns[2])
										   );
					
					items.put(Integer.parseInt(columns[0]),hero);
				}
			}
		}
		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;
		}
	}
}
