<?

//exec ("echo $pid > /tmp/pid");

include "config.php";
include "function.php";

//set the pid for this php file
$pid=getmypid();
$a=writepid($pid);
if ($a) { exec ("echo $pid > /tmp/pid"); }

$connection=connectdb();

// Work-a-round
$prefsquery="select * from prefs";
$prefsresult=mysql_query($prefsquery, $connection);
$prefsrow=mysql_fetch_array($prefsresult);

//while the play is set to YES play the jukebox 
while ($prefsrow[play]== "y") {

	//only playlist files
	$playlistquery="select * from playlist order by id limit 1";
	$playlistresult=mysql_query($playlistquery, $connection);
	$row=mysql_fetch_array($playlistresult);

	if ($row["filename"]!=null) {
		
		//insert the mp3 that is currently playing into the prefs table
		$insertquery="update prefs set currentplay='".addslashes($row["filename"])."'";
		$insertresult=mysql_query($insertquery, $connection);
		
		//delete the mp3 that is playing from the playlist
		$deletequery="DELETE FROM playlist WHERE filename='".addslashes($row["filename"])."'";
		$deleteresult=mysql_query($deletequery, $connection);
		exec("$mp3player -q -volume 100 \"".$filedir."/".$row["filename"]."\"");
	
	//if the playlist is empty start playing random songs by genre if defined
	} elseif ($prefsrow[randomplay] == "y") {
	
		if ($prefsrow[genre] == all){
		$randomgenrequery ="select id,filename,counter FROM files ORDER BY RAND()";
		}
		elseif ($prefsrow[genre] !=null && $prefsrow[genre] !=all){
		$queryor=str_replace(","," || genreid=",$prefsrow[genre]);
		$randomgenrequery= "select id,filename,counter FROM files where genreid=$queryor ORDER BY RAND()";
		}

		if ($prefsrow[genre] ==null){
		die ("no cant do :(");
		}

		//$randomquery="select id,filename,counter FROM files ORDER BY RAND()";
		$randomresult=mysql_query($randomgenrequery, $connection);
		$row=mysql_fetch_array($randomresult);
	
		$counter=$row[counter]; $counter++;
		//if (!$counter) { $counter="1"; }
		$counterquery="update files set counter='$counter' where id='$row[id]'";
		$counterresult=mysql_query($counterquery, $connection);
		echo $counterquery."\n";
		
		if ($row[filename]!="") {
			
			//also the current mp3 same as playlist stuff
			$insertquery="update prefs set currentplay='".addslashes($row["filename"])."'";
			$insertresult=mysql_query($insertquery, $connection);

			exec("$mp3player -q -volume 100 \"".$filedir."/".$row["filename"]."\"");
		} else { echo "Error"; }

	// if playlist is empty and randomplay is off... just wait for the playlist.
	} elseif ($prefsrow[randomplay]=="n") {
		// work-a-round
		$row[filename]=true;
		sleep (2);
	}

	
	if (!$row[filename]) { die("Hmmm"); }

	$prefsquery="select * from prefs";
	$prefsresult=mysql_query($prefsquery, $connection);
	$prefsrow=mysql_fetch_array($prefsresult);
}

if ($prefsrow[play]=="n"){
	$queryon="update prefs set play='y'";
	$resultprefs=mysql_query($queryon, $connection);


}
?>

