package cnrg.itx.datax.devices;

import javax.media.sound.sampled.*;
import cnrg.itx.datax.*;
import java.io.*;


//This is a test of Sun's JavaSound. I tested it with build 086 on NT and had problems with simultaneous play
//and record. 
//NOTE: as of 8/16, Java Sound is not ready for prime time. Give this a try with a build after #086.



public class JSpeakerDestination implements cnrg.itx.datax.Destination {
	
	
	/* ***************Members************************/
	
	private static int BUFFER_SIZE = 8000; //enough for 1 sec. (This is BIG!)
	
	private Mixer mixer = null;
	
	private OutputChannel spkr = null;
	
	private int recieved = 0;
	
	/* ******************Methods**********************/
	
	
	
	public JSpeakerDestination() throws cnrg.itx.datax.DataException{
		
		FileOutputStream fos = null;
		PrintWriter pw = null;
		try {
			fos = new FileOutputStream("JSpeakerDest debug.txt");
			pw = new PrintWriter(fos);
			
		} catch (Throwable th) {
		}
		
		
		//setup the default ITX audio properites
		AudioFormat itxAudio = new AudioFormat(AudioFormat.Encoding.PCM_UNSIGNED,8000,8,1,8,8000); 
 
		mixer = AudioSystem.getMixer(null); //get the system's default mixer
		try {
			spkr = mixer.getOutputChannel(itxAudio, BUFFER_SIZE);
					
		} catch (AudioUnavailableException e2) {
			System.err.println("AudioUnavailableException: " + e2);
			throw new cnrg.itx.datax.DataException(e2.getMessage());
		}
		
		
	}
	
	public void close(){
		spkr.close();
		mixer.close();
	}
	
	public boolean mute(boolean state) {
		return true;		
	}
	
	public void write(byte[] data){
		spkr.write(data,0,data.length);
		recieved += data.length;
	}
	
	
	
	
	/**
	 * Method to get the statistics for the speaker device.
	 * @return Stats the statistics for the speaker device
	 */
	public Stats getStatistics() 
	{ 
		Stats st = new cnrg.itx.datax.Stats();
		st.addStat("<JSpeakerDestination> Bytes Recieved", new Integer(recieved));
		st.addStat("<JSpeakerDestination> Bytes in Buffer",new Integer(BUFFER_SIZE - spkr.available()));
		return st;
	}
	
	/**
	 * Returns a collection of properties supported.
	 */ 
	public PropertiesCollection getProperties() throws DataException
	{
		return null;
	}

	/**
	 * Sets the given properties collection into the device
	 */
	public void setProperties(PropertiesCollection pc) throws DataException
	{
	}

	/**
	 * Interface to set the given properties collection into the device. WOrks under the 
	 * assumption that this is the properties collection of the peer.
	 */
	public void setPeerProperties(PropertiesCollection pc) throws DataException
	{	
	}
}
	

