#include "mof/sound/WaveFile.hpp"
#include "mof/ConsoleIO.hpp"

mof::WaveFile::WaveFile(void)
{
	m_impl = new mof::CWaveFile();
}

mof::WaveFile::~WaveFile(void)
{
	m_impl->close();
	delete m_impl;
}


bool mof::WaveFile::open(const mof::tstring& filename){
	WAVEFORMATEX format;
	if(FAILED(m_impl->open((LPTSTR)filename.c_str() , &format , WAVEFILE_READ)))return false;
    return true;

}


bool mof::WaveFile::close(){
  
	if(FAILED(m_impl->close()))return false;
    return true;


}


long mof::WaveFile::read( BYTE* pBuffer1, long bufferSize1 , BYTE* pBuffer2 , long bufferSize2 ){
   

	DWORD actualReadSize1 = 0;
	DWORD offset = 0;
	for(offset = 0 ; offset < bufferSize1 ; offset += actualReadSize1){
		if(FAILED(m_impl->read(pBuffer1 + offset , bufferSize1 - offset , &actualReadSize1)))return -1;
		else if(actualReadSize1 == 0)break;
		else if(bufferSize1 - offset != actualReadSize1)resetFile();
		
	}

	if(bufferSize2 < 0)return actualReadSize1;

	DWORD actualReadSize2 = 0;
	for(offset = 0 ; offset < bufferSize2 ; offset += actualReadSize2){
		if(FAILED(m_impl->read(pBuffer2 + offset , bufferSize2 - offset, &actualReadSize2)))return -1;
		else if(actualReadSize2 == 0)break;
		else if(bufferSize2 - offset != actualReadSize2)resetFile();
	}

	return actualReadSize1 + actualReadSize2;

}


long mof::WaveFile::getSize(){
	return m_impl->getSize();
}



bool mof::WaveFile::resetFile(){
	if(FAILED(m_impl->resetFile()))return false;
    return true;
}


WAVEFORMATEX* mof::WaveFile::getFormat(){
	return m_impl->getFormat();
}


