#include <errno.h>
#include <string.h>
#include <stdio.h>
#include <unistd.h>
#include <signal.h>
#include <string.h>
#include <stdlib.h>
#include "soundio-util.h"
#include "soundio-demo.h"

#define CHECK_RET(ret) do {		\
	printf("%s ...\n", #ret);	\
	r = (ret);			\
	if (r < 0) {			\
		op = #ret;		\
		goto fail;		\
	}				\
} while (0)

#define CHECK_EXIT(h) do {					\
	void *buf = NULL;					\
	char *bin = (h)->argv[0];				\
	size_t nbytes = 0;					\
	int r;							\
								\
	if ((h)->status >= 0)					\
		printf("%s exit with code %d\n",		\
		       bin, (h)->status);			\
	else							\
		printf("%s is killed by signal %s\n",		\
		       bin, strsignal(-(h)->status));		\
								\
	r = loop_read_all((h)->_err, &buf, &nbytes, false);	\
	if (r < 0)						\
		fprintf(stderr,					\
			"%s: failed to read worker's stderr:%s",\
			bin, strerror(-r));			\
	else if (r > 0) {					\
		printf("*** %s's stderr ***:\n", bin);		\
		fwrite(buf, nbytes, 1, stdout);			\
		puts("");					\
	}							\
	free(buf);						\
} while (0)

int main(int argc, char *argv[], char *envp[])
{
	WorkerHandle h;
	char *op = NULL;
	int r;
	int left, right;
	int percent;

	ignore_signals(SIGPIPE, -1);

	worker_handle_init(&h);
	CHECK_RET(record_start(&h, "sample.wav"));
	sleep(5);
	CHECK_RET(record_stop(&h));
	CHECK_EXIT(&h);
	worker_handle_uninit(&h);

	worker_handle_init(&h);
	CHECK_RET(play_start(&h, "sample.wav"));
	sleep(1);
	CHECK_RET(play_pause(&h));
	sleep(1);
	CHECK_RET(play_continue(&h));
	sleep(3);
	CHECK_RET(play_stop(&h));
	CHECK_EXIT(&h);
	worker_handle_uninit(&h);
	
	worker_handle_init(&h);
	CHECK_RET(mixer_start(&h));
	CHECK_RET(mixer_get_play_vol(&h, &left, &right));
	printf("Volume: left:%d%%, right:%d%%\n", left, right);

	percent = 45;
	printf("Volume set to %d%%\n", percent);
	CHECK_RET(mixer_set_play_vol(&h, &percent));
	printf("Volume is now: %d%%\n", percent);
	printf("\n");

	percent = 55;
	printf("Volume set to %d%%\n", percent);
	CHECK_RET(mixer_set_play_vol(&h, &percent));
	printf("Volume is now: %d%%\n", percent);

	mixer_stop(&h);
	CHECK_EXIT(&h);
	worker_handle_uninit(&h);

	return 0;

fail:
	if (op)
		fprintf(stderr, "Failed to %s: %s\n", op, strerror(-r));
	else
		fprintf(stderr, "Unknown error: %s\n", strerror(-r));

	if (h.pid) {
		CHECK_RET(worker_stop(&h));
		CHECK_EXIT(&h);
	}

	worker_handle_uninit(&h); 

	return 1;
} 
