#include <string.h>
#include <gst/gst.h>
#include <gst/app/gstappsink.h>

int
main(int argc, char *argv[])
{
	static GMainLoop *loop;
	static GstElement *pipeline;
	static GstElement *subparse;

	gst_init(&argc, &argv);

        if (argc != 3) {
                fprintf(stderr, "Usage: %s <URI> <SUBURI>\n", argv[0]);
                exit(1);
        }
        char *uri = argv[1];
        char *suburi = argv[2];

	loop = g_main_loop_new(NULL, FALSE);

	pipeline = gst_element_factory_make("playbin2", NULL);

	g_object_set(G_OBJECT(pipeline), "uri", uri, NULL);
	g_object_set(G_OBJECT(pipeline), "suburi", suburi, NULL);

#if 1
	/* make my custom text-sink */
	GstElement *subbin;
	GstElement *appsink;

	subbin = gst_bin_new("subbin");
	subparse = gst_element_factory_make("subparse", NULL);
	appsink = gst_element_factory_make("appsink", NULL);

	gst_bin_add_many(GST_BIN(subbin), subparse, appsink, NULL);
	gst_element_link_many(subparse, appsink, NULL);

	GstPad *ghostpad;
	GstPad *subparsesink;
	subparsesink = gst_element_get_static_pad(subparse, "sink");
	ghostpad = gst_ghost_pad_new("sink", subparsesink);
	g_object_unref(G_OBJECT(subparsesink));
	gst_element_add_pad(subbin, ghostpad);

	g_object_set(G_OBJECT (pipeline), "text-sink", subbin, NULL);
#endif

	/* set to PAUSED */
        GstStateChangeReturn state_return;
        state_return = gst_element_set_state (pipeline, GST_STATE_PAUSED);

	GstState state;
	/* make sure that the state is PAUSED */
	gst_element_get_state (pipeline, &state, NULL, GST_CLOCK_TIME_NONE);
	/* seek to 0 */
        gst_element_seek_simple (pipeline, GST_FORMAT_TIME, (GstSeekFlags)(GST_SEEK_FLAG_FLUSH), 0);

	GstFormat format;
	gint64 cur;

	format = GST_FORMAT_TIME;
	if (gst_element_query_position(pipeline, &format, &cur)) {
		fprintf(stdout, "position: %016lld\n", cur);
	} else {
		fprintf(stdout, "position query failed\n");
	}

        //state_return = gst_element_set_state (pipeline, GST_STATE_PLAYING);

	g_main_loop_run(loop);
	gst_element_set_state(pipeline, GST_STATE_NULL);
	gst_object_unref(GST_OBJECT(pipeline));
	exit(0);
}
