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.Enemy.Enemy;
import rpgEngine.Data.Abstract.Enemy.EnemyParty;

public class EnemyPartyPool {
	private static EnemyPartyPool instance;
	private Dictionary<Integer,EnemyParty> items;
	
	private EnemyPartyPool() {
		items = new Hashtable<Integer,EnemyParty>();
		loadData();
	}
	
	
	public static EnemyPartyPool getInstance() {
		if(instance == null) {
			instance = new EnemyPartyPool();
		}
		
		return instance;
	}
	
	
	public EnemyParty getPoolItem(Integer i) {
		EnemyParty item = null;
		
		try 
		{
			item = items.get(i);	
		}
		catch(Exception e) 
		{
			return null;	
		}
		
		return item;
	}
	
	
	private void loadData() {	
		String filename = "enemyparty.cfg";
		String[] columns = null;
		InputStream fileStream = null;
		BufferedReader reader = null;
		String line = "";
		
		String[] enemyColumns = null;
		Integer ID = 0;
		EnemyParty enemyParty = null;
		Integer enemyID = 0;
		Enemy enemy = null;
		Boolean boss = false;
		
		
		
		//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]);
					
					enemyColumns = columns[1].split(":");
					
					enemyParty = new EnemyParty(ID);
					
					for(Integer i = 0; i < enemyColumns.length; i++) {
						enemyID = Integer.valueOf(enemyColumns[i]);
						
						enemy = EnemyPool.getInstance().getPoolItem(enemyID);
						
						enemyParty.getEnemies().add(enemy);
					}
					
					if(columns[2].equals("BOSS")) {
						boss = true;
					}
					else {
						boss = false;
					}
					
					enemyParty.setIsBossBattle(boss);
					
					items.put(ID, enemyParty);
				}
			}
		}
		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;
		}
	}
	
}
