#include <stdio.h>

#include <gst/gst.h>
#include <gst/video/video.h>

#include <Platform/Platform.h>
#include <cassert>
#include <stdlib.h>

static GstElement* m_pipeline;
static GMainLoop* m_gstMainLoop;

gboolean s_busCallback(GstBus *bus, GstMessage *msg, gpointer data)
{
    return TRUE;
}

int main(int argc, char **argv)
{
    if( argc!=2 )
    {
        printf("Usage: FakeSinkTest URI\n");
        printf("Example: StateTest file:///c:/Videos/video.mp4\n");
        return 0;
    }
    gst_init(&argc, &argv);

    m_gstMainLoop = g_main_loop_new(NULL, FALSE);
    assert(m_gstMainLoop);

    const char *m_uri = argv[1];

    m_pipeline = gst_element_factory_make("playbin", "playbin0");
    assert(m_pipeline);

    GstBus *bus = gst_pipeline_get_bus(GST_PIPELINE(m_pipeline));
    assert(bus);

    guint m_busWatchId = gst_bus_add_watch (bus, s_busCallback, NULL);
    gst_object_unref(bus);

    GstElement *sink = gst_element_factory_make("fakesink", "fakesink0");
    if( !sink )
    {
        printf("Failed to create sink\n");
    }
    else
    {
        printf("Sink set\n");
        gst_base_sink_set_sync((GstBaseSink*)sink,TRUE);
        g_object_set(G_OBJECT(m_pipeline), "video-sink", sink, NULL);
    }

    g_object_set(G_OBJECT (m_pipeline), "uri", m_uri, NULL);
    gst_element_set_state(m_pipeline, GST_STATE_PAUSED);

    printf("Set state to PLAYING\n");
    gst_element_set_state(m_pipeline, GST_STATE_PLAYING);

    g_main_loop_run(m_gstMainLoop);
    printf("Never reached\n");
}

//Crashes with stacktrace:
// * thread #28: tid = 0x6c2323, 0x00007fff976d1fa0 IOSurface`IOSurfaceDecrementUseCount + 9, name = 'gstglcontext', stop reason = EXC_BAD_ACCESS (code=1, address=0x434f4e54)
//   * frame #0: 0x00007fff976d1fa0 IOSurface`IOSurfaceDecrementUseCount + 9
//     frame #1: 0x000000010b1bb047 libgstapplemedia.so`_io_surface_memory_destroy + 39
//     frame #2: 0x000000010b1fcaa1 libgstgl-1.0.0.dylib`_destroy_gl_objects + 33
//     frame #3: 0x000000010b21233d libgstgl-1.0.0.dylib`_run_message_sync + 29
//     frame #4: 0x000000010b2122f7 libgstgl-1.0.0.dylib`_run_message_async + 23
//     frame #5: 0x000000010005c9c6 libglib-2.0.0.dylib`g_main_context_dispatch + 326
//     frame #6: 0x000000010005ccf4 libglib-2.0.0.dylib`g_main_context_iterate + 420
//     frame #7: 0x000000010005d01f libglib-2.0.0.dylib`g_main_loop_run + 223
//     frame #8: 0x000000010b1f96af libgstgl-1.0.0.dylib`gst_gl_context_create_thread + 575
//     frame #9: 0x000000010008444a libglib-2.0.0.dylib`g_thread_proxy + 90
//     frame #10: 0x00007fff95056268 libsystem_pthread.dylib`_pthread_body + 131
//     frame #11: 0x00007fff950561e5 libsystem_pthread.dylib`_pthread_start + 176
//     frame #12: 0x00007fff9505441d libsystem_pthread.dylib`thread_start + 13
