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.Raw.Sound.GenericSound;
import rpgEngine.Data.Raw.Sound.MP3Sound;
import rpgEngine.Data.Raw.Sound.MidiSound;


public class SoundPool {
	private static SoundPool instance;
	private Dictionary<Integer,GenericSound> items;
	
	public static final int SOUND_TITLE = 0;
	public static final int SOUND_BATTLE = 1;
	public static final int SOUND_BOSS_BATTLE = 2;
	public static final int SOUND_SHOP = 3;
	
	private SoundPool() {
		items = new Hashtable<Integer,GenericSound>();
		loadData();
	}
	
	
	public static SoundPool getInstance() {
		if(instance == null) {
			instance = new SoundPool();
		}
		
		return instance;
	}
	
	
	public GenericSound getPoolItem(Integer i) {
		GenericSound item = null;
		
		try 
		{
			item = items.get(i);	
		}
		catch(Exception e) 
		{
			return null;	
		}
		
		return item;
	}
	
	
	private void loadData() {	
		String filename = "sound.cfg";
		String[] columns = null;
		InputStream fileStream = null;
		BufferedReader reader = null;
		String line = "";
		GenericSound sound = 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()) {
				sound = null;
				line = reader.readLine();
				
				columns = line.split(",");
				
				if(columns[0].equals("ID") == false) {
					if(columns[2].endsWith("mid")) {
						sound = new MidiSound(columns[1],columns[2]);
					}
					else if(columns[2].endsWith("mp3")) {
						sound = new MP3Sound(columns[1],columns[2]);
					}
					
					if(sound != null) {
						items.put(Integer.parseInt(columns[0]),sound);
					}
				}
			}
		}
		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;
		}
	}
}
