#include "CSongParser.h"
#include "CSGD_FModManager.h"
#include "CBeatAnalyzer.h"
#include "Debug.h"
#include <fstream>
#include <string>

CSongParser::CSongParser(void)
{
	m_fvBeatTimes.clear();
}

CSongParser::~CSongParser(void)
{
}

void CSongParser::SetupSong(int nSoundID, double difficultyModifier)
{
	CSGD_FModManager* pFM = CSGD_FModManager::GetInstance();
	FMOD_OUTPUTTYPE backup;
	unsigned int position;
	Channel* pChannel;
	m_nSoundID = nSoundID;
	CBeatAnalyzer* beatAnalyzer = new CBeatAnalyzer(nSoundID, difficultyModifier);

	pFM->GetSystemObject()->getOutput(&backup);
	pFM->GetSystemObject()->setOutput(FMOD_OUTPUTTYPE_NOSOUND_NRT);

	
	pFM->PlaySoundA(nSoundID);
	pChannel = pFM->GetChannel(nSoundID);
	pChannel->setMute(true);
	pChannel->getPosition(&position, FMOD_TIMEUNIT_MS);

	while(position < pFM->GetSoundLength(nSoundID))
	{
		
		int temp = pFM->GetSoundLength(nSoundID);
		CONSOLEMSG << "Position: " << position << "     Song Length: " << temp << "\n\n";
		/////
		// Possible problem with updating too fast
		static float timer = 0.0f;
		static float prevTime = (float)GetTickCount();
		timer += (float)GetTickCount() - prevTime;
		prevTime = (float)GetTickCount();
		if(timer > 0.001f)
		{
			if(beatAnalyzer->IsBeat())
			{
				if(!m_fvBeatTimes.size())
					m_fvBeatTimes.push_back(position);
				else if((position - m_fvBeatTimes[m_fvBeatTimes.size()-1]) > 100)
					m_fvBeatTimes.push_back(position);
			}

			pFM->GetSystemObject()->update();
			timer = 0;
		}

		pChannel->getPosition(&position, FMOD_TIMEUNIT_MS);
		if(!pFM->IsSoundPlaying(nSoundID))
			break;
	}
	CONSOLEMSG << "Done Loading Song Data...\n\n";
	pChannel->setMute(false);
	pFM->StopSound(nSoundID);
	pFM->GetSystemObject()->setOutput(backup);
}

void CSongParser::SaveFile(char* pSongLocation)
{
	m_nSoundID = CSGD_FModManager::GetInstance()->LoadSound(pSongLocation);
	char null = 0;
	//std::string s = CSGD_FModManager::GetInstance()->GetSoundFileName(m_nSoundID);
	SetupSong(m_nSoundID, 30.8142857);
	//const char* c = s.c_str();
	std::string pFileName = pSongLocation;
	pFileName += ".bin";
	/*char szBuffer[256] = {};
	strcpy_s(szBuffer, strlen(pSongLocation)+1, pSongLocation);*/
	std::fstream fout(pFileName.c_str(), std::ios_base::binary | std::ios_base::out);
	/*std::size_t n = strlen(pSongLocation)+1;
	fout.write((char*)&n, sizeof(std::size_t));
	fout.write(szBuffer, sizeof(szBuffer));*/
	//fout.write("\0", 1);
	std::size_t numBeats = m_fvBeatTimes.size();
	fout.write((char*)&numBeats, sizeof(std::size_t));
	for(std::size_t i=0; i<m_fvBeatTimes.size(); ++i)
		fout.write((char*)&m_fvBeatTimes[i], sizeof(unsigned int));
	fout.close();

	CSGD_FModManager::GetInstance()->StopSound(m_nSoundID);
	
}