#pragma once
#include <mof/sound/DirectSoundDevice.hpp>
#include <dsound.h>
#include <mof/ConsoleIO.hpp>


namespace mof
{
namespace sound
{
//{{{ constructor
		DirectSoundDevice::DirectSoundDevice(HWND hWnd)
			: pSound_(NULL), primary_buffer_(NULL)
		{
			HRESULT hr;

			hr = DirectSoundCreate8( NULL, &pSound_, NULL );
			if( FAILED( hr ) ){
				*ConsoleOut::getInstance() << _T("Failed --- CreateDirectSound"); 
				return; 
			}
		
			if( FAILED(hr = pSound_->SetCooperativeLevel( hWnd, DSSCL_PRIORITY ))) {
				throw std::runtime_error("failed to set cooperative level");
			}

			DSBUFFERDESC desc;
			ZeroMemory(&desc, sizeof(desc));
			desc.dwSize = sizeof(desc);
			desc.dwFlags = DSBCAPS_PRIMARYBUFFER;
			desc.dwBufferBytes = 0;// バッファサイズは自動設定される
			desc.lpwfxFormat = NULL;
			if (FAILED(hr = pSound_->CreateSoundBuffer(&desc, &primary_buffer_, NULL))) {
				throw std::runtime_error("failed to create a primary buffer");
			}
			
			// バッファサイズを得る
			DSBCAPS caps;
			caps.dwSize = sizeof(DSBCAPS);
			primary_buffer_->GetCaps(&caps);
			DEBUG_PRINT("primary size" << caps.dwBufferBytes);

			primary_buffer_->Play(0, 0xffffffff, DSBPLAY_LOOPING);
		}
//}}}
//{{{ destructor
		DirectSoundDevice::~DirectSoundDevice()
		{
			primary_buffer_->Release();
			pSound_->Release();
		}
//}}}	
//{{{ raw
		LPDIRECTSOUND8 DirectSoundDevice::raw() const {return pSound_;}
//}}}
//{{{ primary_buffer_
		LPDIRECTSOUNDBUFFER DirectSoundDevice::primary_buffer() const {return primary_buffer_;}
//}}}
}// sound
}// mof
