#include "mof/sound/StreamSoundBuffer.hpp"
#include "mof/ConsoleIO.hpp"
#include "mof/sound/StreamingSoundLoader.hpp"
#include "mof/sound/DirectSoundDevice.hpp"


mof::StreamSoundBuffer::StreamSoundBuffer
(
 	std::shared_ptr<mof::sound::DirectSoundDevice> pDevice,
	LPDIRECTSOUNDBUFFER8 pBuffer,
	LPDIRECTSOUNDNOTIFY8 pSoundNotify,
	SoundFile* pResource
)
: mof::SoundBuffer(pDevice, pBuffer , pResource), initialized_(false)
{
	m_pSoundNotify = pSoundNotify;
	m_pSoundNotify->AddRef();
	m_pLoadingThread = NULL;
	m_pLoadingFunction = NULL;

	
}



mof::StreamSoundBuffer::~StreamSoundBuffer(void)
{
	//boost::mutex::scoped_lock lock(m_pLoadingFunction->getMutex()); TODO これ付けてるとエラーになる
	if(initialized_)
	{
		getSoundBuffer()->Stop();
		m_pLoadingThread->join();
		delete m_pLoadingThread;
		delete m_pLoadingFunction;
	}
	m_pSoundNotify->Release();
}


bool mof::StreamSoundBuffer::initialize(){
	
	/*
	m_pLoadingFunction = new StreamingSoundLoader( getSoundBuffer() , m_pSoundNotify , getResource() );
	m_pLoadingFunction->initialize();
	//m_pLoadingFunction->CopyBlock(0);
	m_pLoadingThread = new boost::thread( boost::ref<StreamingSoundLoader>(*m_pLoadingFunction) );
	*/
	return true;
}


bool mof::StreamSoundBuffer::play(bool looping){
	
	m_pLoadingFunction = new StreamingSoundLoader( getSoundBuffer() , m_pSoundNotify , getResource() );
	m_pLoadingFunction->initialize();
	//m_pLoadingFunction->CopyBlock(0);
	m_pLoadingThread = new boost::thread( boost::ref<StreamingSoundLoader>(*m_pLoadingFunction) );
	initialized_ = true;

	boost::mutex::scoped_lock lock(m_pLoadingFunction->getMutex());
	
	HRESULT hr = getSoundBuffer()->Play( 0 , 0 , (looping)?DSBPLAY_LOOPING : 0);
	if(hr == DSERR_BUFFERLOST){
		*ConsoleOut::getInstance() << _T("Failed --- PlaySound") << std::endl;
		return false;
	}
	return true;
}

void mof::StreamSoundBuffer::pause(){
	//TODO 途中から再生


	//boost::mutex::scoped_lock lock(m_pLoadingFunction->GetMutex());
	getSoundBuffer()->Stop();
	getSoundBuffer()->SetCurrentPosition(0);
	getResource()->resetFile();
	//try{
	m_pLoadingThread->join();
	//}catch(exception e){DEBUG_PRINT(_T("dd"));}
	delete m_pLoadingThread;
	delete m_pLoadingFunction;

	initialized_ = false;
	
	
}
void mof::StreamSoundBuffer::stop(){
	//boost::mutex::scoped_lock lock(m_pLoadingFunction->GetMutex());
	getSoundBuffer()->Stop();
	getSoundBuffer()->SetCurrentPosition(0);
	getResource()->resetFile();
	//try{
	m_pLoadingThread->join();
	//}catch(exception e){DEBUG_PRINT(_T("dd"));}
	delete m_pLoadingThread;
	delete m_pLoadingFunction;

	initialized_ = false;
}
