#!/bin/env python3
import argparse
import sys

from gi.repository import GLib, Gst


Gst.init(sys.argv)


class Example:
    def __init__(self, uri, track_type):
        self.type = track_type
        self.playbin = Gst.ElementFactory.make("playbin", None)
        self.playbin.set_property("uri", uri)
        bus = self.playbin.get_bus()
        bus.connect("message", self.on_message)
        bus.add_signal_watch()
        self.main_loop = GLib.MainLoop()

    def on_message(self, bus, message):
        if message.type == Gst.MessageType.EOS:
            self.quit()
        elif message.type == Gst.MessageType.ERROR:
            _, error_message = message.parse_error()
            print("Error: {}".format(error_message))
            self.quit()

    def on_tick(self):
        current_track = self.playbin.get_property("current-{}".format(self.type))
        next_track = 1     
        print("Switching {} track from {} to {}".format(self.type, current_track, next_track))
        self.playbin.set_property("current-{}".format(self.type), next_track)
        return False

    def run(self):
        self.playbin.set_state(Gst.State.PLAYING)
        self.timeout_callback = GLib.timeout_add_seconds(1, self.on_tick)
        self.main_loop.run()

    def quit(self):
        GLib.source_remove(self.timeout_callback)
        self.playbin.set_state(Gst.State.NULL)
        self.main_loop.quit()

if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("uri")
    parser.add_argument("type", nargs="?", default="audio")
    args = parser.parse_args()
    Example(args.uri, args.type).run()
