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.Skill;



public class SkillPool {

	private static SkillPool instance;
	private Dictionary<Integer,Skill> items;
	
	private SkillPool() {
		items = new Hashtable<Integer,Skill>();
		loadData();
	}
	
	
	public static SkillPool getInstance() {
		if(instance == null) {
			instance = new SkillPool();
		}
		
		return instance;
	}
	
	
	public Skill getPoolItem(Integer i) {
		Skill item = null;
		
		try 
		{
			item = items.get(i);	
		}
		catch(Exception e) 
		{
			return null;	
		}
		
		return item;
	}
	
	
	private void loadData() {	
		String filename = "skills.cfg";
		String[] columns = null;
		InputStream fileStream = null;
		BufferedReader reader = null;
		String line = "";
		Skill skill = null;
		Integer ID = -1;
		
		Integer basedOnStat = Skill.STAT_ATTACK;
		Integer type = Skill.TYPE_ATTACK;
		Integer target = Skill.TARGET_SINGLE;
		
		
		//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("Attack")) {
						type = Skill.TYPE_ATTACK;
					}
					else if(columns[2].equals("Heal")) {
						type = Skill.TYPE_HEALING;
					}
					else if(columns[2].equals("Revive")) {
						type = Skill.TYPE_REVIVE;
					}
					else {
						type = Skill.TYPE_ATTACK;
					}
					
					if(columns[3].equals("Single")) {
						target = Skill.TARGET_SINGLE;
					}
					else if(columns[3].equals("All")) {
						target = Skill.TARGET_ALL;
					}
					else {
						target = Skill.TARGET_SINGLE;
					}
					
					if(columns[7].equals("Magic")) {
						basedOnStat = Skill.STAT_MAGIC;
					}
					else if(columns[6].equals("Attack")) {
						basedOnStat = Skill.STAT_ATTACK;
					}
					else {
						basedOnStat = Skill.STAT_MAGIC;
					}
					
					skill = new Skill(ID,columns[1],columns[6],type,target,Integer.parseInt(columns[4]),Integer.parseInt(columns[5]),basedOnStat);
					
					items.put(Integer.parseInt(columns[0]),skill);
				}
			}
		}
		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;
		}
	}
}
