#include "main.h"
#include "sound.h"
#include "ya_random.h"

static Mix_Music *mus;

#define FREQUENCY 22050
#define CHANNELS 2

void Snd_Init(void)
{
	if (Mix_OpenAudio(FREQUENCY, AUDIO_S16SYS, CHANNELS, 576))
		fatal_error("Error opening audio: %s\n", Mix_GetError());
	mus = NULL;
}

void Snd_Close(void)
{
	Mix_CloseAudio();
}

void Snd_PlayMusic(const char *name, bool loop)
{
	if (mus)
		Mix_FreeMusic(mus);
	mus = NULL;

	char file[strlen("Music/.ogg")+strlen(name)+1];
	sprintf(file,"Music/%s.ogg",name);

	mus = Mix_LoadMUS(find_file(file));
	if (!mus)
		fatal_error("Error loading music: %s", Mix_GetError());

	Mix_PlayMusic(mus, loop ? -1 : 0);
}

void Snd_StopMusic(void)
{
	Mix_FadeOutMusic(1000);
}

Mix_Chunk *noise = NULL;

void Snd_PlayNoise(bool sine)
{
	if (noise)
		return;
	{ // Generate 5 seconds of white noise
		Uint32 i;
		Sint16 junk[5*FREQUENCY*CHANNELS];
		for (i = 0; i < 5*22050; i++)
		{
			if (sine)
			{
				if (i < 2*FREQUENCY)
					junk[i*2] = (sin(i/40)+(frnd()*2.0-1.0))/2.0*0x7FFF;
				else if (i < 3*FREQUENCY)
					junk[i*2] = (sin(i/50)+(frnd()*2.0-1.0))/2.0*0x7FFF;
				else
					junk[i*2] = (sin(i/30)+(frnd()*2.0-1.0))/2.0*0x7FFF;
			}
			else
				junk[i*2] = (frnd()-0.5)*0x7FFF;
			junk[i*2+1] = junk[i*2];
		}
		noise = Mix_QuickLoad_RAW((Uint8 *)junk,5*FREQUENCY*CHANNELS*sizeof(Sint16));
		if (!noise)
			fatal_error("lol out of memory.");
	}
	Mix_VolumeChunk(noise, MIX_MAX_VOLUME/6);
	Mix_PlayChannel(-1,noise,-1);
}

static inline Uint32 free_chunk(Uint32 interval, void *param)
{
	Mix_Chunk *c = (Mix_Chunk *)param;
	Mix_FreeChunk(c);
	return 0;
}

void Snd_StopNoise(void)
{
	if (!noise)
		return;
	Mix_FadeOutChannel(-1,1000);
	SDL_AddTimer(1100,free_chunk,noise);
	noise = NULL;
}
