#include <miniaudio.h>

#include "audio.h"

t_audio	*audio_init(void)
{
	t_audio	*audio;
	ma_engine_config config;

	audio = (t_audio *)malloc(sizeof(t_audio));
	if (!audio)
		return (NULL);
	ft_memset(audio, 0, sizeof(t_audio));
	config = ma_engine_config_init();
	config.pUserData = audio;
	config.pLogCallback = NULL;
	config.logLevel = MA_LOG_LEVEL_INFO;
	if (ma_engine_init(&config, &audio->engine) != MA_SUCCESS)
	{
		free(audio);
		return (NULL);
	}
	return (audio);
}

void audio_uninit(t_audio *audio)
{
	int i;

	if (!audio)
		return ;
	i = 0;
	while (i < SND_SIZE)
	{
		if (audio->sounds[i])
		{
			ma_sound_uninit(&audio->sounds[i]);
			audio->sounds[i] = NULL;
		}
		i++;
	}
	ma_engine_uninit(&audio->engine);
	free(audio);
}

int	audio_load_sounds(t_audio *audio)
{
	int			i;
	const char	*sound_files[SND_SIZE] = {
		"assets/sounds/walk.wav",
		"assets/sounds/flash.wav",
		"assets/sounds/damage.wav",
		"assets/sounds/death.wav",
		"assets/sounds/enemy.wav",
		"assets/sounds/pickup.wav",
		"assets/sounds/hum.wav",
		"assets/sounds/noise.wav"};

	if (!audio)
		return ();
	i = 0;
	while (i < SND_SIZE)
	{
		if (ma_sound_init_from_file(&audio->engine, sound_files[i],
				0, NULL, NULL, &audio->sounds[i]) != MA_SUCCESS)
		{
			audio_uninit(audio);
			return (FAILURE);
		}
		i++;
	}
	return (SUCCESS);
}

int 	audio_play(t_audio *audio, t_sound sound)
{
	if (!audio || sound < 0 || sound >= SND_SIZE || !audio->sounds[sound])
		return (FAILURE);
	ma_sound_seek_to_pcm_frame(audio->sound[sound], 0);
	if (ma_sound_start(&audio->sounds[sound]) != MA_SUCCESS)
		return (FAILURE);
	return (SUCCESS);
}

int audio_stop(t_audio *audio, t_sound sound)
{
	if (!audio || sound < 0 || sound >= SND_SIZE || !audio->sounds[sound])
		return (FAILURE);
	ma_sound_seek_to_pcm_frame(audio->sound[sound], 0);
	if (ma_sound_stop(&audio->sounds[sound]) != MA_SUCCESS)
		return (FAILURE);
	return (SUCCESS);
}

int audio_is_playing(t_audio *audio, t_sound sound)
{
	if (!audio || sound < 0 || sound >= SND_SIZE || !audio->sounds[sound])
		return (FAILURE);
	if (ma_sound_is_playing(&audio->sounds[sound]))
		return (SUCCESS);
	return (FAILURE);
}

int audio_loop(t_audio *audio, t_sound sound)
{
	if (!audio || sound < 0 || sound >= SND_SIZE || !audio->sounds[sound])
		return (FAILURE);
	if (ma_sound_set_looping(&audio->sounds[sound], loop) != MA_SUCCESS)
		return (FAILURE);
	return (SUCCESS);
}

int	audio_handle_queues(t_audio *audio)
{
	int	i;

	if (!audio)
		return (FAILURE);
	i = 0;
	while (i < SND_SIZE)
	{
		if (audio->play_queue[i])
		{
			audio_play(audio, i);
			audio->play_queue[i] = 0;
		}
		if (audio->stop_queue[i])
		{
			audio_stop(audio, i);
			audio->stop_queue[i] = 0;
		}
		audio->is_playing[i] = ma_sound_is_playing(&audio->sounds[i]);
		i++;
	}
	return (SUCCESS);
}

