#include <gst/gst.h>
#include <glib.h>
//#include <stdio.h>
#include <pthread.h>
//#include <time.h>
//#include <stdlib.h>
#include <string.h>

int thread_loop = 1;
GstElement *pipeline, *source;

static gboolean bus_call(GstBus *bus, GstMessage *msg, gpointer data){

	GMainLoop *loop = (GMainLoop *) data;

	switch (GST_MESSAGE_TYPE(msg)) {
		case GST_MESSAGE_EOS:
			g_print("End of stream\n");
			//thread_loop=0;
			//g_main_loop_quit(loop);
                        gst_element_seek_simple(GST_ELEMENT(pipeline), GST_FORMAT_TIME, GST_SEEK_FLAG_FLUSH | GST_SEEK_FLAG_KEY_UNIT, 0); 
			g_print("Restart\n");
                        break;
		case GST_MESSAGE_ERROR: {
			gchar *debug;
			GError *error;

			gst_message_parse_error(msg, &error, &debug);
			g_free(debug);

			g_printerr("Error: %s\n", error->message);
			g_error_free(error);
			g_main_loop_quit(loop);
			break;
		}
	default:
		break;
	}
	return TRUE;
}

int main(int argc, char* argv[]) {

	if(argc < 2){
		printf("usege: ./programname filename\n");
		return -1;
	}

	GMainLoop *loop;
	pthread_t volume;

//	GstElement *pipeline, *source;
	GstBus *bus;

	gst_init(&argc, &argv);

	loop = g_main_loop_new(NULL, FALSE);

	pipeline = gst_pipeline_new("audio-player");
	source = gst_element_factory_make("playbin2", "file-source");

	if (!pipeline || !source) {
		g_printerr("One element could not be created. Exiting.\n");
		return -1;
	}
	void *set_volume(void *arg) {
		double n;
		while(thread_loop!=0){
			n = random()%1000;
			//g_object_set(G_OBJECT(source), "volume", n/1000, NULL);
			
                        GValue vol = { 0, };
                        g_value_init (&vol, G_TYPE_DOUBLE);
                        g_value_set_double (&vol, n/1000.0);
                        g_object_set_property(G_OBJECT(source), "volume", &vol);

                        printf("Volume changed: %f.\n", n/1000);
			sleep(0,1);
		}
		pthread_exit(0);
	}
	char* file = "file://";
	char* dest = argv[1];
	int size = strlen(file) + strlen(dest);
	char* destination = (char*) malloc(size*(sizeof(char)));
	sprintf(destination, file);
	strcat(destination, dest);
	printf("argv: %s\n", destination);
	g_object_set(G_OBJECT(source), "uri", destination, NULL); //still crashes with the path written instead of "destination"

	pthread_create(&volume,NULL,set_volume,(void*) 1);

	bus = gst_pipeline_get_bus(GST_PIPELINE(pipeline));
	gst_bus_add_watch(bus, bus_call, loop);
	gst_object_unref(bus);

	gst_bin_add_many(GST_BIN(pipeline), source,  NULL);

	g_print("Playing...\n");
	gst_element_set_state(pipeline, GST_STATE_PLAYING);

	g_print("Running...\n");
	g_main_loop_run(loop);

	g_print("Returned, stopping playback\n");
	gst_element_set_state(pipeline, GST_STATE_NULL);

	g_print("Deleting pipeline\n");
	gst_object_unref(GST_OBJECT(pipeline));

	return 0;
}
