#include "SoundBuffer.hpp"
#include "SoundFile.hpp"
#include <mof/ConsoleIO.hpp>
#include <mof/sound/DirectSoundDevice.hpp>

mof::SoundBuffer::SoundBuffer
(
	std::shared_ptr<mof::sound::DirectSoundDevice> pDevice,
	LPDIRECTSOUNDBUFFER8 pBuffer,
	SoundFile* pResouce
)
	: m_pBuffer(pBuffer), m_pResource(pResouce), pDevice_(pDevice)
{
	//m_pBuffer->AddRef();
	pBuffer->GetFrequency(&default_frequency_);
}

mof::SoundBuffer::~SoundBuffer(void){
		m_pBuffer->Release();
		delete m_pResource;
}

//{{{ is_playing 
bool mof::SoundBuffer::is_playing() const
{
	DWORD status;
	m_pBuffer->GetStatus(&status);
	return status & DSBSTATUS_PLAYING;
}
//]}}
//{{{ update
void mof::SoundBuffer::update()
{
	volume_stream_.update();
	frequency_stream_.update();

	mof::real volume = volume_stream_.value();
	if (volume > 1) volume = 1;
	else if (volume < 0) volume = 0;
	int converted_volume = (1.0f - volume) * DSBVOLUME_MIN;
	converted_volume = converted_volume < DSBVOLUME_MIN
		? DSBVOLUME_MIN
		: converted_volume > DSBVOLUME_MAX
			? DSBVOLUME_MAX
			: converted_volume;
	LONG prev_volume;
	getSoundBuffer()->GetVolume(&prev_volume);
	if (converted_volume != prev_volume) {
		getSoundBuffer()->SetVolume(converted_volume);// 必要ない場合は変更を行わない
	}
	
	mof::real frequency = frequency_stream_.value();
	int converted_frequency = default_frequency_ * frequency;
	converted_frequency = converted_frequency < DSBFREQUENCY_MIN 
			? DSBFREQUENCY_MIN  
			: converted_frequency > DSBFREQUENCY_MAX 
				? DSBFREQUENCY_MAX
				: converted_frequency;
	DWORD prev_frequency;
	getSoundBuffer()->GetFrequency(&prev_frequency);
	if (converted_frequency != prev_frequency) {
		getSoundBuffer()->SetFrequency(converted_frequency);// 必要ない場合は変更を行わない
	}
	
}
//}}}
