/*
Copyright (c) 2006, Geomatics and Cartographic Research Centre, Carleton 
University All rights reserved.

Redistribution and use in source and binary forms, with or without 
modification, are permitted provided that the following conditions are met:

 - Redistributions of source code must retain the above copyright notice, 
   this list of conditions and the following disclaimer.
 - Redistributions in binary form must reproduce the above copyright notice,
   this list of conditions and the following disclaimer in the documentation
   and/or other materials provided with the distribution.
 - Neither the name of the Geomatics and Cartographic Research Centre, 
   Carleton University nor the names of its contributors may be used to 
   endorse or promote products derived from this software without specific 
   prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE 
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 
POSSIBILITY OF SUCH DAMAGE.

$Id$
*/
package ca.carleton.gcrc.atlas;

import java.net.URL;

import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.Clip;
import javax.sound.sampled.FloatControl;
import javax.sound.sampled.Mixer;
import javax.sound.sampled.LineUnavailableException;

public class ClipTrack extends AudioTrack {
	
	private Mixer.Info preferredMixerInfo;

	public ClipTrack(URL url_, String origUrlString_, Mixer.Info mi_) {
		super(url_, origUrlString_);
		preferredMixerInfo = mi_;
	}

	public static void main(String[] args) {

//		Track soundtest;
//		URL url;
//
//		try {
//			// url = new
//			// URL("http://devel0.gcrc.carleton.ca/~amoshayes/test.au");
//			url = new URL(
//					"http://devel0.gcrc.carleton.ca/~glennbrauen/liberal_martin.ogg");
//			System.out.println("Loading Sound...");
//			soundtest = new ClipTrack(url);
//			soundtest.setShouldLoop(true);
//			soundtest.setPlaying(true);
//			System.out.println("Sound played.");
//		} catch (MalformedURLException e) {
//			System.out.println("Error.");
//			e.printStackTrace();
//		}
	}

	protected void changeGain() {
		float dB;

		if (null != m_gainControl) {
			dB = computeGainIndB();
			m_gainControl.setValue(dB);
		}
	}

	protected void loadSound() {
		// This runs on the LoadThread thread. Needs to be called from the LoadThread class but not from outside.
		
		Clip clip = null;
		
		m_inputStream = getAndConvertAudioInputStream();
		
		if (null != m_inputStream) {
			try {
				DataLine.Info info = new DataLine.Info(Clip.class,
						m_inputStream.getFormat(), AudioSystem.NOT_SPECIFIED);
				
				try {
					// first attempt to get a clip off the preferred mixer...
					Mixer mix = AudioSystem.getMixer(preferredMixerInfo);
					m_currentDataLine = (Clip) mix.getLine(info);
					clip = (Clip) m_currentDataLine;
					clip.open(m_inputStream);
					DebugLog("ClipTrack::loadSound: fetched clip from preferred mixer - " + preferredMixerInfo.toString());
				} catch (LineUnavailableException ex) {
					try {
						// Preferred failed - try to get line off default mixer.
						// Depending on where the attempt with the preferred mixer failed (most 
						// common cause is that the clip is too big for the Java Sound Audio Engine
						// - limit is equivalent of 1048576 samples of 4 bytes each (i.e. a 4M buffer)),
						// the clip should probably be closed and the inputStream needs to be recreated.
						if (null != clip) {
							clip.close();
						}
						m_currentDataLine = null;
						if (null != m_inputStream) {
							m_inputStream.close();
						}
						m_inputStream = getAndConvertAudioInputStream();

						m_currentDataLine = (Clip) AudioSystem.getLine(info);
						clip = (Clip) m_currentDataLine;
						clip.open(m_inputStream);
						DebugLog("ClipTrack::loadSound: fetched clip from default mixer.");
					} catch (Exception defClipEx) {
						defClipEx.printStackTrace();
						return;
					}
				} catch (Exception prefClipEx) {
					prefClipEx.printStackTrace();
					return;
				}
				
				m_gainControl = (FloatControl) m_currentDataLine.getControl(FloatControl.Type.MASTER_GAIN);
			} catch (Exception ex) {
				ex.printStackTrace();
				return;
			}
			changeGain();
			playSourceLine();
		}
	}

	protected void playSourceLine() {
		
		Clip temp;
		
		if (null != m_currentDataLine) {
			temp = (Clip) m_currentDataLine;
			
			DebugLog("ClipTrack::playSourceLine(): " + m_url + " - playing(" + m_isPlaying + ") paused(" +
					m_isPaused + ") loop(" + m_shouldLoop + ")");
			
			if (true == m_isPlaying && false == m_isPaused) {
				// Check if it is already playing
				if (false == temp.isActive()) {
					temp.stop();
					temp.setFramePosition(0); // resets to start but otherwise looping starts from position of last stop
					if (true == m_shouldLoop) {
						temp.setLoopPoints(0, -1); // loop over whole clip
						temp.loop(Clip.LOOP_CONTINUOUSLY);
					} else {
						temp.loop(0);
					}
					temp.start();
				}
			} else { // Not playing
				temp.stop();
			}
		}
	}

}