using System;
using System.Windows.Forms;
using System.IO;
using Microsoft.DirectX;
using Microsoft.DirectX.DirectSound;
using System.Threading;

namespace MhsApplication
{

	/// <summary>
	/// Summary description for PlantPatchSoundRenderer.
	/// </summary>
	public class PlantPatchSoundRenderer
	{
		private Device dsDevice = null;
		private SecondaryBuffer dsBuffer = null;
		private int bufferBytes = 0;
		private bool isPlaying = false;

		public PlantPatchSoundRenderer(Control owner)
		{
			InitializeDirectSound(owner);
			LoadSoundFile("C:\\Documents and Settings\\axjww\\Desktop\\CS470 Software project\\mhs\\sounds\\a.wav");
		}

		private bool InitializeDirectSound(Control owner)
		{
			try
			{
				dsDevice = new Device();
				dsDevice.SetCooperativeLevel(owner, CooperativeLevel.Priority);
			}
			catch
			{
				MessageBox.Show("Unable to create sound device. Sample will now exit.");
				return false;
			}
			return true;
		}

		private bool LoadSoundFile(string name)
		{
			try
			{
//				FileStream fs = new FileStream(name,FileMode.Open);
//				BufferDescription bdesc = new BufferDescription();
//				bdesc.BufferBytes = (int)fs.Length;
//				bufferBytes = bdesc.BufferBytes;
//				dsBuffer = new SecondaryBuffer(fs, (int)fs.Length, bdesc,dsDevice);

				System.Reflection.Assembly assembly = System.Reflection.Assembly.GetExecutingAssembly();
				System.IO.Stream stream = assembly.GetManifestResourceStream("MhsApplication.a.wav");
				BufferDescription bdesc = new BufferDescription();
				bdesc.BufferBytes = (int)stream.Length;
				bufferBytes = bdesc.BufferBytes;
				dsBuffer = new SecondaryBuffer(stream, (int)stream.Length, bdesc,dsDevice);
				stream.Close();
			}
			catch(Exception)
			{
				MessageBox.Show("Unable to setup sound buffer.");
				return false;
			}
			return true;
		}

		public void PlayTick()
		{

			 //play 1/100th of a second
			while( isPlaying )
				Thread.Sleep(50);

			isPlaying = true;
			int bytesToPlay = (int) Math.Round (((float)dsBuffer.Format.AverageBytesPerSecond) * .01f);
			dsBuffer.SetCurrentPosition( bufferBytes - bytesToPlay);
			dsBuffer.Play(0,0);
			isPlaying = false;
		}

		public void PlayBeep()
		{
			//play 1/10th of a second
			while( isPlaying )
				Thread.Sleep(50);

			isPlaying = true;
			int bytesToPlay = (int) Math.Round (((float)dsBuffer.Format.AverageBytesPerSecond) * .1f);
			dsBuffer.SetCurrentPosition( bufferBytes - bytesToPlay);
			dsBuffer.Play(0,0);
			isPlaying = false;
		}

	}
}
