#include <stdio.h>

#include "../../src/util/error.h"
#include "../../src/util/memory.h"
#include "../../src/util/audio.h"


static char *wav_filename;
static audio_Type *wave;


static int menu()
{
	printf("%s, %d s, %d Hz:\n",
		wav_filename,
		(audio_getOriginalLengthMilliseconds(wave) + 500) / 1000,
		audio_getCurrentSamplesPerSecond(wave));
	printf("   p)lay, P)ause, l)oop, o)ne-shot, r)ewind, +-)pitch, q)uit: ");
	char c;
	scanf("%c", &c);
	printf("\n");
	return c;
}


int main(int argc, char *argv[])
{
	if (argc == 1) {
		wav_filename = "audio-sine-400hz-2sec.wav";
	} else if (argc == 2) {
		wav_filename = argv[1];
	} else {
		printf("Usage: audio-test.exe [WAV_FILE]\n");
		exit(1);
	}
	
	wave = audio_new(wav_filename);
	if( wave == NULL ){
		printf("ERROR: audio_new(%s) failed\n", wav_filename);
		return 1;
	}
	
	int quit = 0;
	while( ! quit ) {
		int c = menu();
		switch(c){
			
		case 'q':
			quit = 1;
			break;
		
		case 'p':
			audio_play(wave);
			break;
		
		case 'P':
			audio_pause(wave);
			break;
			
		case 'l':
			audio_loop(wave, 1);
			break;
			
		case 'o':
			audio_loop(wave, 0);
			break;
			
		case 'r':
			audio_setCurrentPositionMilliseconds(wave, 0);
			break;
			
		case '+':
			audio_setCurrentSamplesPerSecond(wave, 1.2 * audio_getCurrentSamplesPerSecond(wave));
			break;
			
		case '-':
			audio_setCurrentSamplesPerSecond(wave, audio_getCurrentSamplesPerSecond(wave) / 1.2);
			break;
		}
	}
	
	memory_dispose(wave);

	return 0;
}
