package rpgEngine.Logic.Game;

import rpgEngine.Data.Abstract.Game;
import rpgEngine.Data.Raw.Sound.GenericSound;
import rpgEngine.Resources.SoundPool;
import rpgEngine.UI.GenericPanel;
import rpgEngine.UI.MainFrame;



public class MusicPlayer {
	private static MusicPlayer instance;
	private GenericSound currentSound;
	private Thread currentSoundThread;
	
	private MusicPlayer() {
		currentSound = null;
		currentSoundThread = null;
	}
	
	
	public static MusicPlayer getInstance() {
		if(instance == null) {
			instance = new MusicPlayer();
		}
		
		return instance;
	}
	
	
	public void playSound(GenericSound newSound) {
		
		if(newSound == currentSound) {
			return;
		}
		
		stopSound();
		
		currentSound = newSound;

		if(currentSound != null) {
			//currentSound.play();
			currentSoundThread = new Thread() {
                public void run() {
                    try { 
                    	currentSound.play(); 
                    }
                    catch (Exception e) { 
                        System.out.println(e); 
                    }
                }
            };
			
            currentSoundThread.start();
            
		}
	}
	
	
	@SuppressWarnings("deprecation")
	public void stopSound() {
		
		if(currentSound == null) {
			return;
		}
		
		if(currentSoundThread == null) {
			return;
		}
		
		currentSound.stop();
		currentSoundThread.stop();
		
		currentSound = null;
	}
	
	
	public void changeMusicBasedOnScreen(MainFrame mf) {
		GenericPanel panel = mf.getActivePanel();
		Game game = mf.getGame();
		GenericSound oldMusic = currentSound;
		GenericSound newMusic = null;
		
		if(panel.getID() == MainFrame.PANEL_BATTLE) {
			if(game.getActiveEnemyParty().isBossBattle()) {
				newMusic = SoundPool.getInstance().getPoolItem(SoundPool.SOUND_BOSS_BATTLE); 
			}
			else {
				newMusic = SoundPool.getInstance().getPoolItem(SoundPool.SOUND_BATTLE);
			}
		}
		else if(panel.getID() == MainFrame.PANEL_GAME) {
			newMusic = game.getActiveMap().getBackgroundMusic();
		}
		else if(panel.getID() == MainFrame.PANEL_TITLE) {
			newMusic = SoundPool.getInstance().getPoolItem(SoundPool.SOUND_TITLE);
		}
		else if(panel.getID() == MainFrame.PANEL_SHOP) {
			newMusic = SoundPool.getInstance().getPoolItem(SoundPool.SOUND_SHOP);
		}
		
		if(newMusic != null) {
			if(newMusic != oldMusic) {
				stopSound();
				playSound(newMusic);
			}
		}
	}
}
