#include "jsound.h"
#include "jfile.h"
#include <string>

Mix_Music *music = NULL;
char currentMusic[12];

bool JS_Init() {
	Mix_OpenAudio(MIX_DEFAULT_FREQUENCY, MIX_DEFAULT_FORMAT, 2, 1024);
	Mix_AllocateChannels(8);
	currentMusic[0] = 0;
	return true;
}

void JS_LoadMusic(const char *musicFilename)
{
	if (music != NULL) { 
		Mix_HaltMusic();
		Mix_FreeMusic(music);
	}
	Mix_VolumeMusic(MIX_MAX_VOLUME);

	int filesize = 0;
	char *buffer = JF_GetBufferFromResource(musicFilename, filesize);
	
	SDL_RWops *rw = SDL_RWFromMem(buffer, filesize);
	music = Mix_LoadMUS_RW(rw, 1);
	strcpy(currentMusic, musicFilename);
}

void JS_SetMusicVolume(int volume) {
	Mix_VolumeMusic(volume);
}

void JS_PlayMusic(int loops) {
	Mix_PlayMusic(music, loops);
}

void JS_PauseMusic() {
	Mix_PauseMusic();
}

void JS_FadeOutMusic() {
	Mix_FadeOutMusic(500);
}

bool JS_MusicPlaying() {
	return (Mix_PlayingMusic() == 1);// && (Mix_FadingMusic() != MIX_FADING_OUT);
}

const char* JS_GetMusicName() {
	return currentMusic;
}

JS_Sound *JS_LoadSound(char *soundFilename) {
	int filesize = 0;
	char *buffer = JF_GetBufferFromResource(soundFilename, filesize);
	
	SDL_RWops *rw = SDL_RWFromMem(buffer, filesize);
	return Mix_LoadWAV_RW(rw, false);
}

void JS_SetSoundVolume(JS_Sound *sound, int volume) {
	Mix_VolumeChunk(sound, volume);
}

void JS_PlaySound(JS_Sound *sound) {
	Mix_PlayChannel(-1, sound, 0);
}

void JS_FreeSound(JS_Sound *sound) {
	Mix_FreeChunk(sound);
}

void JS_Finalize() {
	Mix_FreeMusic(music);
	Mix_CloseAudio();
}

