
#include "music.hh"

static const char*	music_extensions[MUSIC_COUNT_EXTENSIONS] =
{
	".it",
	".mod",
	".mp3",
	".ogg",
	".s3m",
	".xm"
};

int		music_init (struct s_music* music)
{
	music->play = false;

	return 0;
}

void	music_play_defined (struct s_music* music, const char* path)
{
	if (music->play)
		music_stop (music);

	CHD_LoadStream (path, FMOD_DEFAULT, &music->music);
	CHD_PlayStart (music->music, 0);

	music->play = true;
}

void	music_play_random (struct s_music* music, const char* path)
{
	std::vector<std::string>	list;
	Browse						browse;
	unsigned int				i;

	if (browse.Open (path))
		while (browse.Next ())
			if (!browse.IsDir ())
				for (i = 0; i < MUSIC_COUNT_EXTENSIONS; ++i)
					if (!strcasecmp (browse.GetFile ().substr (browse.GetFile ().length () - strlen (music_extensions[i]), 16).c_str (), music_extensions[i]))
						list.push_back (browse.GetFull ());

	if (list.size () > 0)
		music_play_defined (music, list[rand () % list.size ()].c_str ());
}

void	music_free (struct s_music* music)
{
	music_stop (music);

	// free structure
}

void	music_stop (struct s_music* music)
{
	if (music->play)
	{
		CHD_PlayStop (music->music);
		// free music

		music->play = false;
	}
}
