Gst.Element playbin;
string uri;

bool become_ready () {
	print ("change to ready\n");
	playbin.set_state (Gst.State.READY);
	return false;
}

void about_to_finish (Gst.Element playbin, void* user_data) {
	playbin.set ("uri", uri);
	Idle.add (become_ready);
}

void bus_message (Gst.Bus bus, Gst.Message message) {
	switch (message.type) {
		case Gst.MessageType.STATE_CHANGED:
			if (message.src == playbin) {
				Gst.State old_state, new_state, pending;
				message.parse_state_changed (out old_state, out new_state, out pending);
				print ("got state change: %s to %s pend %s\n", Gst.Element.state_get_name (old_state),
						Gst.Element.state_get_name (new_state), Gst.Element.state_get_name (pending));
			}
			break;

		case Gst.MessageType.STREAM_START:
			print ("stream-start\n");
			break;

		case Gst.MessageType.ERROR:
			Error error;
			string debug;
			message.parse_error (out error, out debug);
			print ("debug: %s\n", debug);
			throw error;

		default:
			if (message.src == playbin) {
				print ("got a %x %s message\n", (uint) message.type, Gst.MessageType.get_name(message.type));
			}
			break;
	}
}

int main (string[] args) {
	Gst.init (ref args);

	if (args.length != 2) {
		printerr ("must give one .ogg file to cmdline\n");
		return 1;
	}

	var file = File.new_for_commandline_arg (args[1]);
	uri = file.get_uri ();

	print ("using uri %s\n", uri);

	playbin = Gst.ElementFactory.make ("playbin", null);
	var bus = playbin.get_bus ();
	bus.add_signal_watch ();
	bus.message.connect (bus_message);
	playbin.connect ("signal::about-to-finish", about_to_finish, null);
	playbin.set ("uri", uri);
	playbin.set_state (Gst.State.PLAYING);

	while (true) {
		MainContext.default ().iteration (true);
	}
}
