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


public class ShopPool {
	private static ShopPool instance;
	private Dictionary<Integer,Shop> items;
	
	private ShopPool() {
		items = new Hashtable<Integer,Shop>();
		loadData();
	}
	
	
	public static ShopPool getInstance() {
		if(instance == null) {
			instance = new ShopPool();
		}
		
		return instance;
	}
	
	
	public Shop getPoolItem(Integer i) {
		Shop item = null;
		
		try 
		{
			item = items.get(i);	
		}
		catch(Exception e) 
		{
			return null;	
		}
		
		return item;
	}
	
	
	private void loadData() {
		String filename = "shops.cfg";
		String[] columns = null;
		InputStream fileStream = null;
		BufferedReader reader = null;
		String line = "";;
		
		Shop shop = null;
		Item item = null;
		Integer id = null;
		Integer itemID = 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();
				
				if(line.startsWith("ID:")) {
					id = Integer.parseInt(line.substring(3));
					shop = new Shop();

					shop.setID(id);
					
					items.put(id, shop);
				}
				else if(line.startsWith("ITEM:")) {
					columns = line.split(":");
					itemID = Integer.valueOf(columns[1]);
					
					item = ItemPool.getInstance().getPoolItem(itemID);
					
					shop.getItems().add(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;
		}
	}
	

	
}
