package com.stereodustparticles.mooler_caster_console;

// SDP Mooler Caster Console
// Ridiculously simple radio DJ program, with a 16-slot soundboard and 2-deck music player
// Written by Ben A. (IfYouLikeGoodIdeas)

// This class defines the player thread for a Deck

import java.awt.Color;

import javax.sound.sampled.AudioFormat;
import javax.swing.JOptionPane;

public class DeckThread extends Thread {
	private boolean playing = true;
	private Deck deck;
	
	public DeckThread(Deck deck) {
		this.deck = deck;
	}
	
	public void run() {
		// Get info about the stream for use in calculating the current time position (for time display)
		AudioFormat format = deck.audio.getFormat();
		int bytesPerTenth = ((int)format.getSampleRate() / 10) * (format.getSampleSizeInBits() / 8) * format.getChannels();
		int byteCounter = 0;
		
		// http://www.javazoom.net/mp3spi/documents.html
		if (deck.line != null) {
			// Change Play button to Stop button
			deck.fields.playButton.setBackground(Color.RED);
			deck.fields.playButton.setText("STOP");
			
			// Start the output line
			deck.line.start();
			
			// Create variables to track bytes read and written
		    int nBytesRead = 0;
		    int nBytesWritten = 0;
		    
		    // While there is data left to read and we haven't been told to stop...
		    while ( nBytesRead != -1 && playing ) {
		        try {
					// Read some data into the buffer
		        	nBytesRead = deck.audio.read(deck.playBuffer, 0, deck.playBuffer.length);
		        	
		        	// If EOF hasn't been reached...
					if (nBytesRead != -1) {
						// Write the data we got out to the audio line
						nBytesWritten = deck.line.write(deck.playBuffer, 0, nBytesRead);
						
						// Add the number of bytes written to our running tally
						byteCounter += nBytesWritten;
						
						// If our running tally has reached a tenth of a second (or more) worth of data...
						if ( byteCounter > bytesPerTenth ) {
							// Decrement a tenth of a second off our remaining time
							deck.remain--;
							
							// Subtract that tenth of a second from our byte count
							byteCounter -= bytesPerTenth;
							
							// Update the counter and progress bar
							deck.updateTime(deck.remain);
						}
			        }
				}
		        catch (Exception e) {
					// Something has gone (very) wrong
		        	JOptionPane.showMessageDialog(SDPConsole.getMainWindow(), "Deck playback failed with the following error: " + e.getMessage() + "\n\nMicrowave your music playback computer, then try again.", "Deck Playback Error", JOptionPane.ERROR_MESSAGE);
					e.printStackTrace();
					break;
				}
		    }
		    
		    // Done playing - drain the line and stop
		    deck.line.drain();
		    deck.line.stop();
		    
		    // Change the Stop button back to Play
		    deck.fields.playButton.setBackground(Color.GREEN);
		    deck.fields.playButton.setText("PLAY");
		    
		    // Reset timer colors to normal (to avoid getting stuck in red)
		    deck.fields.time.setForeground(Color.BLACK);
			deck.fields.progress.setForeground(Deck.DEFAULT_PROGRESS_BAR_COLOR);
		}
		
		// End the thread
		return;
	}
	
	// Stop playback
	public void stopAudio() throws InterruptedException {
		// Notify the thread that it should stop
		playing = false;
		
		// Wait until the playback thread has finished before returning
		join();
	}
}
