// RASAudioDlg.cpp : implementation file
//

#include "stdafx.h"
#include "RASAudio.h"
#include "RASAudioDlg.h"

#include "OpenBoardPortDlg.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif


/////////////////////////////////////////////////////////////////////////////
// CAboutDlg dialog used for App About

class CAboutDlg : public CDialog
{
public:
	CAboutDlg();

// Dialog Data
	//{{AFX_DATA(CAboutDlg)
	enum { IDD = IDD_ABOUTBOX };
	//}}AFX_DATA

	// ClassWizard generated virtual function overrides
	//{{AFX_VIRTUAL(CAboutDlg)
	protected:
	virtual void DoDataExchange(CDataExchange* pDX);    // DDX/DDV support
	//}}AFX_VIRTUAL

// Implementation
protected:
	//{{AFX_MSG(CAboutDlg)
	//}}AFX_MSG
	DECLARE_MESSAGE_MAP()
};

CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD)
{
	//{{AFX_DATA_INIT(CAboutDlg)
	//}}AFX_DATA_INIT
}

void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(CAboutDlg)
	//}}AFX_DATA_MAP
}

BEGIN_MESSAGE_MAP(CAboutDlg, CDialog)
	//{{AFX_MSG_MAP(CAboutDlg)
		// No message handlers
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()


/////////////////////////////////////////////////////////////////////////////
// CRASAudioDlg dialog

static UINT SampleThreadFunction(LPVOID pParam)
{
   CRASAudioDlg * pDlg = (CRASAudioDlg *)pParam;
   ASSERT(pDlg != NULL);

   enum
   {
      EVENT_STARTSAMPLING = 0,
      EVENT_GETSAMPLEDONE,
      EVENT_EXIT,
      EVENT_COUNT,
   };

   CSyncObject * apEvents[EVENT_COUNT];
   apEvents[EVENT_STARTSAMPLING] = &(pDlg->m_evStartSampling);
   apEvents[EVENT_GETSAMPLEDONE] = &(pDlg->m_evGetSampleDone);
   apEvents[EVENT_EXIT]          = &(pDlg->m_evExitSampleThread);

   CMultiLock Wait(apEvents, EVENT_COUNT);
   BOOL fKeepGoing = TRUE;

   while (fKeepGoing)
   {
      BYTE abSample[2048];
      DWORD cbSampled = 0;
      SHIM_STATUS eShimStatus = SHIM_STATUS_SUCCESS;

      if (pDlg->m_fSampling)
      {
         pDlg->m_Adapter.GetSamples(abSample, sizeof(abSample), &cbSampled,
                                    500, pDlg->m_evGetSampleDone, &eShimStatus);
      }

      switch (Wait.Lock(2000, FALSE))
      {
         case WAIT_OBJECT_0 + EVENT_STARTSAMPLING:
         {
            TRACE("SampleThreadFunction(): Prodded\n");
            break;
         }

         case WAIT_OBJECT_0 + EVENT_GETSAMPLEDONE:
         {
            TRACE("SampleThreadFunction(): Sample is ready\n");

            TRACE("Shim status is %d\n", eShimStatus);
            if ((eShimStatus == SHIM_STATUS_SUCCESS) && (cbSampled > 0))
            {
               if (pDlg->m_fOutputToWaveOutDev)
                  pDlg->m_WaveOutDev.Write(abSample, cbSampled);

               if (pDlg->m_fOutputToWaveOutFile)
                  pDlg->m_WaveOutFile.Write(abSample, cbSampled);
            }

            break;
         }
         
         case WAIT_OBJECT_0 + EVENT_EXIT:
         {
            TRACE("SampleThreadFunction(): Exiting\n");
            fKeepGoing = FALSE;
            break;
         }

         case WAIT_TIMEOUT:
         {
            TRACE("SampleThreadFunction(): Timed out\n");
            break;
         }

         default:
         {
            TRACE("SampleThreadFunction(): What the ... !\n");
            ASSERT(FALSE);
            break;
         }
      }
   }

   return 0;
}

CRASAudioDlg::CRASAudioDlg(CWnd* pParent /*=NULL*/)
	: CDialog(CRASAudioDlg::IDD, pParent)
{
	//{{AFX_DATA_INIT(CRASAudioDlg)
	m_strBoardPortName = _T("");
	m_strWaveDevOutName = _T("");
	m_strWaveFileOutName = _T("");
	//}}AFX_DATA_INIT
	// Note that LoadIcon does not require a subsequent DestroyIcon in Win32

	m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);

   m_fFoundComatibleWaveOutDev = m_WaveOutDev.FindCompatibleDev();
	m_strWaveDevOutName = (m_fFoundComatibleWaveOutDev) ? m_WaveOutDev.GetName() : _T("No compatible device found");

   m_fSampling = FALSE;
   m_fSourceSelected = FALSE;
   m_fOutputToWaveOutDev = m_fFoundComatibleWaveOutDev;
   m_fOutputToWaveOutFile = FALSE;
   m_strWaveFileOutPath = _T("");

   m_strBoardName = _T("");
   m_strPortName = _T("");
   m_nPort = 0;

   m_pSampleThread = AfxBeginThread(SampleThreadFunction, this, THREAD_PRIORITY_NORMAL, 0, CREATE_SUSPENDED);
   ASSERT(m_pSampleThread != NULL);

   m_pSampleThread->SetThreadPriority(THREAD_PRIORITY_TIME_CRITICAL);
   m_pSampleThread->m_bAutoDelete = FALSE;
   m_pSampleThread->ResumeThread();
}

CRASAudioDlg::~CRASAudioDlg()
{
   // shut down the sample thread
   m_evExitSampleThread.SetEvent();
   ::WaitForSingleObject(m_pSampleThread->m_hThread, 10000);
   delete m_pSampleThread;
}

void CRASAudioDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(CRASAudioDlg)
	DDX_Control(pDX, IDC_CHECK_ENABLE_STEREO, m_ctlEnableStereo);
	DDX_Control(pDX, IDC_OPEN_WAVEDEVOUT_BUTTON, m_ctrlWaveDevOutButton);
	DDX_Control(pDX, IDC_OPEN_WAVEFILEOUT_BUTTON, m_ctrlOpenWaveFileOutButton);
	DDX_Control(pDX, IDC_STOP_BUTTON, m_ctrlStopButton);
	DDX_Control(pDX, IDC_RECORD_BUTTON, m_ctrlRecordButton);
	DDX_Control(pDX, IDC_OPEN_BOARDPORT_BUTTON, m_ctrlOpenBoardPortButton);
	DDX_Control(pDX, IDC_PLAY_BUTTON, m_ctrlPlayButton);
	DDX_Text(pDX, IDC_BOARDPORT_NAME, m_strBoardPortName);
	DDX_Text(pDX, IDC_WAVEDEVOUT_NAME, m_strWaveDevOutName);
	DDX_Text(pDX, IDC_WAVEFILEOUT_NAME, m_strWaveFileOutName);
	//}}AFX_DATA_MAP
}

BEGIN_MESSAGE_MAP(CRASAudioDlg, CDialog)
	//{{AFX_MSG_MAP(CRASAudioDlg)
	ON_WM_SYSCOMMAND()
	ON_WM_PAINT()
	ON_WM_QUERYDRAGICON()
	ON_BN_CLICKED(IDC_OPEN_BOARDPORT_BUTTON, OnOpenBoardPortButton)
	ON_BN_CLICKED(IDC_PLAY_BUTTON, OnPlayButton)
	ON_BN_CLICKED(IDC_OPEN_WAVEFILEOUT_BUTTON, OnOpenWaveFileOutButton)
	ON_BN_CLICKED(IDC_RECORD_BUTTON, OnRecordButton)
	ON_BN_CLICKED(IDC_STOP_BUTTON, OnStopButton)
	ON_BN_CLICKED(IDC_OPEN_WAVEDEVOUT_BUTTON, OnOpenWaveDevOutButton)
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CRASAudioDlg message handlers

BOOL CRASAudioDlg::OnInitDialog()
{
	CDialog::OnInitDialog();

	// Add "About..." menu item to system menu.

	// IDM_ABOUTBOX must be in the system command range.
	ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);
	ASSERT(IDM_ABOUTBOX < 0xF000);

	CMenu* pSysMenu = GetSystemMenu(FALSE);
	if (pSysMenu != NULL)
	{
		CString strAboutMenu;
		strAboutMenu.LoadString(IDS_ABOUTBOX);
		if (!strAboutMenu.IsEmpty())
		{
			pSysMenu->AppendMenu(MF_SEPARATOR);
			pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);
		}
	}

	// Set the icon for this dialog.  The framework does this automatically
	//  when the application's main window is not a dialog
	SetIcon(m_hIcon, TRUE);			// Set big icon
	SetIcon(m_hIcon, FALSE);		// Set small icon

   m_ctrlOpenBoardPortButton.SetIcon(AfxGetApp()->LoadIcon(IDI_BOARD));
   m_ctrlOpenWaveFileOutButton.SetIcon(AfxGetApp()->LoadIcon(IDI_FLOPPY));

   m_ctrlPlayButton.SetIcon(AfxGetApp()->LoadIcon(IDI_PLAY));
   m_ctrlStopButton.SetIcon(AfxGetApp()->LoadIcon(IDI_STOP));
   m_ctrlRecordButton.SetIcon(AfxGetApp()->LoadIcon(IDI_RECORD));

   UpdateButtonIcons();
	
	return TRUE;  // return TRUE  unless you set the focus to a control
}

void CRASAudioDlg::OnSysCommand(UINT nID, LPARAM lParam)
{
	if ((nID & 0xFFF0) == IDM_ABOUTBOX)
	{
		CAboutDlg dlgAbout;
		dlgAbout.DoModal();
	}
	else
	{
		CDialog::OnSysCommand(nID, lParam);
	}
}

// If you add a minimize button to your dialog, you will need the code below
//  to draw the icon.  For MFC applications using the document/view model,
//  this is automatically done for you by the framework.

void CRASAudioDlg::OnPaint() 
{
	if (IsIconic())
	{
		CPaintDC dc(this); // device context for painting

		SendMessage(WM_ICONERASEBKGND, (WPARAM) dc.GetSafeHdc(), 0);

		// Center icon in client rectangle
		int cxIcon = GetSystemMetrics(SM_CXICON);
		int cyIcon = GetSystemMetrics(SM_CYICON);
		CRect rect;
		GetClientRect(&rect);
		int x = (rect.Width() - cxIcon + 1) / 2;
		int y = (rect.Height() - cyIcon + 1) / 2;

		// Draw the icon
		dc.DrawIcon(x, y, m_hIcon);
	}
	else
	{
		CDialog::OnPaint();
	}
}

// The system calls this to obtain the cursor to display while the user drags
//  the minimized window.
HCURSOR CRASAudioDlg::OnQueryDragIcon()
{
	return (HCURSOR) m_hIcon;
}

void CRASAudioDlg::OnOpenBoardPortButton() 
{
   COpenBoardPortDlg OpenDlg;

   OpenDlg.m_strBoard = m_strBoardName;
   OpenDlg.m_strPort = m_strPortName;
   OpenDlg.m_nPort = m_nPort;

   if (OpenDlg.DoModal() == IDOK)
   {
      m_strBoardName = OpenDlg.m_strBoard;
      m_strPortName = OpenDlg.m_strPort;
      m_nPort = OpenDlg.m_nPort;
      m_Adapter.Attach(m_strBoardName);
      m_strBoardPortName = m_strBoardName + TEXT(" : ") + m_strPortName;
      m_fSourceSelected = TRUE;
      UpdateData(FALSE);
      UpdateButtonIcons();
   }
}

void CRASAudioDlg::OnOpenWaveFileOutButton() 
{
   CFileDialog SaveAsDialog(FALSE, _T("wav"), _T("*.wav"), OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT | OFN_PATHMUSTEXIST, _T("Sounds (*.wav)"), this);
   if (SaveAsDialog.DoModal() == IDOK)
   {
      m_strWaveFileOutPath = SaveAsDialog.GetPathName();
      m_strWaveFileOutName = SaveAsDialog.GetFileName();
      UpdateData(FALSE);
      UpdateButtonIcons();
   }
}

void CRASAudioDlg::OnOpenWaveDevOutButton() 
{
   m_fOutputToWaveOutDev = (m_fFoundComatibleWaveOutDev) ? !m_fOutputToWaveOutDev : FALSE;
   UpdateButtonIcons();
}

void CRASAudioDlg::StartAdapterSampling()
{

   m_Adapter.SetStereo(m_ctlEnableStereo.GetCheck());
   m_Adapter.OpenStream(AUDIOTAP_NAME);
   m_Adapter.StartSampling(m_nPort);
   m_evStartSampling.SetEvent();
}

void CRASAudioDlg::OpenWaveOutDev()
{
   ASSERT(m_fFoundComatibleWaveOutDev);
   int eStatus;

   m_WaveOutDev.Open(&eStatus, (m_ctlEnableStereo.GetCheck()) );
   TRACE("The output wave device is %s\n",
      (eStatus == CWaveOutDev::WOD_OPEN_STATUS_SUCCESS) ? "open" :
      ((eStatus == CWaveOutDev::WOD_OPEN_STATUS_IN_USE) ? "in use" : "broken"));
}

void CRASAudioDlg::OnPlayButton() 
{
   ASSERT(!m_fSampling);
   ASSERT(m_fFoundComatibleWaveOutDev);
   ASSERT(m_fSourceSelected);

   OpenWaveOutDev();

   m_fSampling = TRUE;
   StartAdapterSampling();

   UpdateButtonIcons();
}

void CRASAudioDlg::OpenWaveOutFile()
{
   m_fOutputToWaveOutFile = m_WaveOutFile.Open(m_strWaveFileOutPath, (m_ctlEnableStereo.GetCheck()) );
}

void CRASAudioDlg::OnRecordButton() 
{
   ASSERT(!m_fSampling);
   ASSERT(!m_strWaveFileOutPath.IsEmpty());
   ASSERT(m_fSourceSelected);

   if (m_fFoundComatibleWaveOutDev) OpenWaveOutDev();

   OpenWaveOutFile();

   m_fSampling = TRUE;
   StartAdapterSampling();

   UpdateButtonIcons();
}

void CRASAudioDlg::OnStopButton() 
{
   ASSERT(m_fSampling);

   m_fSampling = FALSE;

   m_Adapter.StopSampling();
   m_Adapter.CloseStream();

   m_WaveOutDev.Close();

   m_WaveOutFile.Close();
   m_fOutputToWaveOutFile = FALSE;

   UpdateButtonIcons();
}

void CRASAudioDlg::UpdateButtonIcons()
{
   m_ctrlWaveDevOutButton.SetIcon(AfxGetApp()->LoadIcon(m_fOutputToWaveOutDev ? IDI_SPEAKER : IDI_SPEAKER_DISABLED));
   m_ctrlPlayButton.EnableWindow(m_fFoundComatibleWaveOutDev && !m_fSampling && m_fSourceSelected);
   m_ctrlStopButton.EnableWindow(m_fSampling);
   m_ctrlRecordButton.EnableWindow(!m_strWaveFileOutPath.IsEmpty() && !m_fSampling);
}
