/*
 *
 * By Hans-Christian Ebke
 *
 * Build with: g++ `pkg-config --cflags clutter-1.0 clutter-gst-1.0` clutterbug.cpp `pkg-config --libs clutter-gst-1.0`
 *
 * Invoke as: ./clutterbug file:///path/to/video1.mkv file:///path/to/video2.mkv
 *
 */

#include <clutter/clutter.h>
#include <clutter-gst/clutter-gst.h>

#include <stdexcept>
#include <iostream>

static bool doOutput = true;
void onPixbufChange(ClutterMedia *vt, void*) {
    if (doOutput) {
        doOutput = false;
        std::cout << "Duration of video: " << clutter_media_get_duration(vt) << std::endl;
    }
}

void onEndOfStream(ClutterMedia *vt, const char *uri) {
    std::cout << "Starting next video." << std::endl;
    clutter_media_set_uri(vt, uri);
    clutter_media_set_playing(vt, true);
    doOutput = true;
}

int main(int argc, char *argv[]) {
	if (CLUTTER_INIT_SUCCESS != clutter_init(&argc, &argv))
		throw std::runtime_error("Initialization of clutter failed.");

	if (CLUTTER_INIT_SUCCESS != clutter_gst_init(&argc, &argv))
		throw std::runtime_error("Initialization of clutter-gst failed.");

    ClutterStage *stage = CLUTTER_STAGE(clutter_stage_get_default());
    static const ClutterColor black = { 0x00, 0x00, 0x00, 0xff }; /* Black */

    clutter_stage_set_color(stage, &black);
    clutter_actor_set_size(CLUTTER_ACTOR(stage), 1280, 720);
    clutter_actor_show(CLUTTER_ACTOR(stage));

    ClutterGstVideoTexture *vt = CLUTTER_GST_VIDEO_TEXTURE(clutter_gst_video_texture_new());
    clutter_container_add_actor(CLUTTER_CONTAINER(stage), CLUTTER_ACTOR(vt));
    clutter_actor_show(CLUTTER_ACTOR(vt));
    
    clutter_media_set_uri(CLUTTER_MEDIA(vt), argv[1]);
    clutter_media_set_playing(CLUTTER_MEDIA(vt), true);

    g_signal_connect(CLUTTER_MEDIA(vt), "pixbuf-change", G_CALLBACK(onPixbufChange), 0);
    g_signal_connect(CLUTTER_MEDIA(vt), "eos", G_CALLBACK(onEndOfStream), argv[2]);

	clutter_main();

	return 0;
}
