/*
 * Created on Dec 5, 2004
 *
 * TODO To change the template for this generated file go to
 * Window - Preferences - Java - Code Style - Code Templates
 */
package WheelOfFortune.game.userOutput;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FilenameFilter;

import javazoom.jl.player.advanced.*;
import javazoom.jl.player.*;

/**
 * @author Dannan
 *
 * TODO To change the template for this generated type comment go to
 * Window - Preferences - Java - Code Style - Code Templates
 */
public class MusicThread{
	private String[] songList;
	private String PATH = ".\\WheelOfFortune\\game\\music\\";
	private int current;
	private PlayThread thread;
	AdvancedPlayer player;
	Player player2;
	boolean shuffle;
	public MusicThread()
	{
		shuffle = false;
		File f = new File(PATH);
		songList = f.list(new FilenameFilter()
				{
			public boolean accept(File f, String s)
			{
				if(s.endsWith(".mp3"))
					return true;
				else
					return false;
			}
		});
		current = 0;
		if(shuffle)
			current = (int)(Math.random()*songList.length);
		
		player2 = null;
	}
	public void setShuffle(boolean s)
	{
		shuffle = s;
	}
	public void play()
	{
		try{
		if(player != null) player.close();
		player = new AdvancedPlayer(new BufferedInputStream(new FileInputStream(new File(PATH + songList[current]))));
		new PlayThread().start();
		
		}
		catch (Exception e) {System.out.println(e); }
	}
	
	public void stopPlay()
	{
		if(player != null) {
			player.close();
		}
	}
	
	
	public void next()
	{
		if(player != null)
		{
			player.close();
		}
		if(shuffle)
			current = (int)(Math.random()*songList.length);
		else
			current= (current+1)%songList.length;
		play();
	}

	
	public class InfoListener extends PlaybackListener
	{
		public void playbackStarted(PlaybackEvent evt)
		{
		}
		
		public void playbackFinished(PlaybackEvent evt)
		{ 
			try {
				current = (int)(Math.random()*songList.length);
				play();
			}
			catch (Exception e) {}
		}
	}
	public class PlayThread extends Thread
	{
		
		public void run()
		{
			try {
			player.play();
			}
			catch (Exception e) {}
		}
	}
}
