#include <glib.h>
#include <gst/gst.h>
#include <gio/gio.h>

char **files;
int file;
int file_length;

GMainLoop *loop = NULL;
GstElement *playbin = NULL;

void on_state_change (GstBus *bus, GstMessage *message, gpointer user_data)
{
    GstState old_state, new_state;

    gst_message_parse_state_changed (message, &old_state, &new_state, NULL);
    if (message->src == G_OBJECT (playbin)) {
        const char *uri;
        g_object_get (playbin, "uri", &uri, NULL);
        g_debug ("File: %s", uri);
        g_debug ("State change: %d -> %d", (int)old_state, (int)new_state);
        if ((old_state == GST_STATE_READY) && 
             (new_state == GST_STATE_PAUSED)) {
            g_debug ("PAUSED");
            file++;
            gst_element_set_state (playbin, GST_STATE_NULL);
            if (file < file_length) {
                GFile *f = g_file_new_for_commandline_arg (files[file]);
                char *uri = g_file_get_uri (f);
                g_object_unref (f);
                g_object_set (G_OBJECT (playbin), "uri", uri, NULL);
                g_free (uri);
                g_debug ("change state: %d", gst_element_set_state (playbin, GST_STATE_PAUSED));
            } else {
                g_main_loop_quit (loop);
            }
        }
    }
}

void on_error (GstBus *bus, GstMessage *message, gpointer user_data)
{
    g_debug ("Error");
    g_main_loop_quit (loop);
}

void on_tag (GstBus *bus, GstMessage *message, gpointer user_data)
{
    g_debug ("Tag");
}

int main (int argc, char *argv[]) {
    GstElement *sink;
    GstBus *bus;
    GFile *f;
    gst_init (&argc, &argv);
    file_length = argc;
    files = argv;
    file = 1;

    playbin = gst_element_factory_make ("playbin2", NULL);
    sink = gst_element_factory_make ("fakesink", NULL);
    g_object_set (G_OBJECT (playbin), "audio-sink", sink, NULL);

    sink = gst_element_factory_make ("fakesink", NULL);
    g_object_set (G_OBJECT (playbin), "video-sink", sink, NULL);

    bus = gst_element_get_bus (playbin);
    gst_bus_add_signal_watch (bus);
    g_signal_connect (bus, "message::state-changed", (GCallback) on_state_change, NULL);
    g_signal_connect (bus, "message::tag", (GCallback) on_tag, NULL);
    g_signal_connect (bus, "message::error", (GCallback) on_error, NULL);
    gst_object_unref (bus);

    if (file < file_length) {
        char *uri;
        f = g_file_new_for_commandline_arg (files[file]);
        uri = g_file_get_uri (f);

        g_object_set (G_OBJECT (playbin), "uri", uri, NULL);
        g_free (uri);
        g_object_unref (f);

        gst_element_set_state (playbin, GST_STATE_PAUSED);

        loop = g_main_loop_new (NULL, FALSE);
        g_main_loop_run (loop);
    }

    gst_object_unref (playbin);

    return 0;
}
