/*  DS
 *  Copyright (C) Joakim Kolsjö and Anders Asplund 2005
 *	This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 
 */ 
 
#include "music.h"

using namespace std;

namespace DS
{
	F_CALLBACKAPI void* cbopen(const char* pName)
	{
		return (void*)pName; // :D
	}
	
	void F_CALLBACKAPI cbclose(void* pHandle) {}
	
	int F_CALLBACKAPI cbread(void* pBuffer, int size, void* pHandle)
	{
		return ((MemFile*)pHandle)->Read(pBuffer, size);
	}
	
	int F_CALLBACKAPI cbseek(void* pHandle, int pos, signed char mode)
	{
		((MemFile*)pHandle)->Seek(pos, mode);
		return 0;
	}
	
	int F_CALLBACKAPI cbtell(void* pHandle)
	{
		return ((MemFile*)pHandle)->Tell();
	}	

	Music::Music(DataReader* pDataReader)
	{
		m_pDataReader = pDataReader;
		m_pSong = 0;
		m_volume = 255;
		m_bHasInit = false;
		m_bHasLoad = false;
//#ifndef WIN32
		FSOUND_File_SetCallbacks(cbopen,
			cbclose,
			 cbread, 
			 cbseek, 
			 cbtell);
//#endif
	}
	
	Music::~Music()
	{
		if(m_pSong)
			FMUSIC_FreeSong(m_pSong);
	}
	
	void Music::Init(int samplerate)
	{
		static char* fn = "[Music::Init]";
		if(!FSOUND_Init(samplerate, 32, 0))
			cout << fn << " Failed to init sound." << endl;
		else
			m_bHasInit = true;
	}
	
	void Music::Load(const char* pFile)
	{
		static char* fn = "[Music::Load]";
		if(m_bHasInit)
		{
//			#ifdef WIN32
//			m_pSong = FMUSIC_LoadSong(((string)"../data/" + pFile).c_str());
//			m_pSong = FMUSIC_LoadSong("ps.xm");
//			#else
			m_pSong = FMUSIC_LoadSong((char*)m_pDataReader->GetFile(pFile));
//			#endif
			FSOUND_SetVolume(FSOUND_ALL, m_volume);
			if(!m_pSong)
				cout << fn << " Failed to load music." << endl;
			FMUSIC_SetLooping(m_pSong, false);
			m_bHasLoad = true;
		}
	}
	
	void Music::Play()
	{
		if(m_bHasLoad)
			if(!FMUSIC_PlaySong(m_pSong))
				cout << "[Music::Play] Failed to play music." << endl;
	}
	
	void Music::Stop()
	{
		if(m_bHasLoad)
			FSOUND_StopSound(FSOUND_ALL);
	}
	
	void Music::SetVolume(int volume)
	{
		m_volume = volume;
		FSOUND_SetVolume(FSOUND_ALL, m_volume);
	}
	
	int Music::GetVolume()
	{
		return m_volume;
	}		
}
