/* MoleInvasion 0.3 - Copyright (C) 2004-2006 - Guillaume Chambraud (linuxprocess@free.fr)

  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. */

#define MIXER_C
#include "mixer.h"


/* here for the moment ...*/
#include <sys/types.h>
#include <dirent.h>
char * giveRandomFile(char* dir,char* ext)
{	DIR *mydir;
	struct dirent *myfile;
	int nb,choix;
	static char buff[255]="";
	
	if(!dir)return NULL;

	mydir=opendir(dir);
	if(!mydir)return NULL;
	nb=0;
	while((myfile=readdir(mydir)))
	{	if(strstr(myfile->d_name, ext))
		{//	fprintf(stderr,"found %s\n",myfile->d_name);
			nb++;
		}
	}
	closedir(mydir);
	
	if(!nb)
		return NULL;
	
	choix=(rand()%nb)+1;
	
	mydir=opendir(dir);
	if(!mydir)return NULL;
	nb=0;
	while((myfile=readdir(mydir)))
	{	if(strstr(myfile->d_name, ext))
		{	nb++;
			if(nb==choix)
			{//	fprintf(stderr,"chose %s\n",myfile->d_name);
				snprintf(buff,sizeof(buff),"%s/%s",dir,myfile->d_name);
				break;
			}
		}
	}
	closedir(mydir);
	if(strlen(buff))
		return buff;
	else
		return NULL;
}


/* static global vars */
static int musicInit=0;

static Mix_Music *music = NULL;
static char * current_music = NULL;

static myList* snd_list;

typedef struct {
	char* file;
	Mix_Chunk *sound;
}sound_struct;

int initTheMusic()
{	int audio_rate = 44100;
	Uint16 audio_format = AUDIO_S16; 
	int audio_channels = 2;
	int audio_buffers = 4096;
	
	if(SDL_Init(SDL_INIT_AUDIO)!=0)
		return -1;
	
	snd_list=InitList();

	if(Mix_OpenAudio(audio_rate, audio_format, audio_channels, audio_buffers))
	{	return -1;
	}
	musicInit=1;
	return 0;
}

int stopTheMusic()
{	if(!g_activate_music)
		return 0;
	if(!music)
		return 0;
	Mix_HaltMusic();
	Mix_FreeMusic(music);
	music = NULL;
	if(current_music)
		free(current_music);
	current_music=NULL;
	return 0;
}

int startTheMusic(char * file)
{	if(!g_activate_music)
		return 0;
	
	if(!musicInit)
	{	if(initTheMusic()!=0)
		{	g_activate_music=0;
			return 0;
		}
	}
	
	if(!file || g_random_music)
		file=giveRandomFile("music",".ogg");
	if(!file)
		return 0;

	/* si on joue la meme musique, on continue */
	if(current_music && !strcmp(file,current_music))
		return 0;

	if(music)
		stopTheMusic();

	music = Mix_LoadMUS(file);
	if(!music)
	{	fprintf(stderr,"Cannot play :%s\n",file);
		return startTheMusic(NULL);
	}
	fprintf(stderr,"Now playing :%s\n",file);
	current_music=(char*)malloc(strlen(file)+1);
	if(current_music)
		strcpy(current_music,file);
	Mix_PlayMusic(music, -1);
	Mix_HookMusicFinished((void(*)())stopTheMusic);
	return 0;
}

int searchSound(char * file)
{	int i;
	for(i=0;i<snd_list->size;i++)
	{	sound_struct* ptr=(sound_struct*)GetPosList(snd_list,i);
		if( ptr == NULL)
		{	fprintf( stderr, "GetPosList(%d,%d) should not be NULL !\n",i,snd_list->size);
			continue;
		}
		if( ptr->file == NULL)
		{	fprintf( stderr, "GetPosList(%d,%d)->file should not be NULL !\n",i,snd_list->size);
			continue;
		}
		if(strcmp(ptr->file,file)==0)
			return i;
	}
	return -1;
}

int startTheSound(char * file)
{	int pos;
	sound_struct the_sound;
	Mix_Chunk * chunk;

	if(!g_activate_sound)
		return 0;
	
	assert(file);
	
	if(!musicInit)
	{	if(initTheMusic()!=0)
		{	g_activate_sound=0;
			return 0;
		}
	}
	pos=searchSound(file);
	if(pos<0)
	{	the_sound.sound = Mix_LoadWAV(file);
		if(!the_sound.sound)
		{	fprintf(stderr,"Cannot load :%s\n",file);
			return 0;
		}
		the_sound.file = (char*)malloc(strlen(file)+1);
		strcpy(the_sound.file,file);
		AddToList(snd_list,&the_sound,sizeof(sound_struct));
		chunk=the_sound.sound;
	}
	else
	{	chunk=((sound_struct*)GetPosList(snd_list,pos))->sound;
	}
	pos=Mix_PlayChannel(-1, chunk, 0);
/*	fprintf(stderr,"playing %s  on :%d\n",file,pos);*/
	return pos;
}

#ifdef NO_DEF

void handleKey(SDL_KeyboardEvent key);

int main(void) {

  SDL_Surface *screen;
  SDL_Event event;
  int done = 0;

  /* Same setup as before */

  SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO);

  screen = SDL_SetVideoMode(320, 240, 0, 0);

  while(!done) {
    while(SDL_PollEvent(&event)) {
      switch(event.type) {
      case SDL_QUIT:
        done = 1;
        break;
      case SDL_KEYDOWN:
      case SDL_KEYUP:
        handleKey(event.key);
        break;
      }
    }
    SDL_Delay(50);
  }

  Mix_CloseAudio();
  SDL_Quit();

}

void handleKey(SDL_KeyboardEvent key) {
  switch(key.keysym.sym) {
  case SDLK_a:
    if(key.type == SDL_KEYDOWN)
	startTheSound("../SDLmix/tintopi.wav");
    break;
  case SDLK_z:
    if(key.type == SDL_KEYDOWN)
	startTheSound("../SDLmix/spark.wav");
    break;
  case SDLK_e:
    if(key.type == SDL_KEYDOWN)
	startTheSound("../SDLmix/trance02.wav");
    break;
  case SDLK_m:
    if(key.type == SDL_KEYDOWN)
        startTheMusic("../SDLmix/Lenvoleespatiale.ogg");
	break;
  case SDLK_l:
    if(key.type == SDL_KEYDOWN)
        stopTheMusic();
	break;
  }
}

#endif
