#!/usr/bin/env python3
import gi
import sys

gi.require_version("Gst", "1.0")
from gi.repository import Gst, GObject


Gst.init(sys.argv)


class Example(object):
    def __init__(self, uri, seek):
        self.seek = seek
    
        self.pipeline = Gst.ElementFactory.make("playbin", None)
        self.pipeline.set_property("uri", uri)
        
        # xvimagesink is broken on my VM
        videosink = Gst.ElementFactory.make("aasink", None)
        self.pipeline.set_property("video-sink", videosink)
        
        self.bus = self.pipeline.get_bus()
        self.bus.add_signal_watch()
        self.bus.connect("message::eos", self.on_eos)
        self.bus.connect("message::error", self.on_error)
        
        self.main_loop = GObject.MainLoop()
        GObject.timeout_add_seconds(3, self.switch_track)
        
    def on_eos(self, bus, message):
        self.pipeline.set_state(Gst.State.NULL)
        self.pipeline.set_state(Gst.State.PLAYING)
        #self.pipeline.seek_simple(Gst.Format.TIME, Gst.SeekFlags.FLUSH, 0.0);
        
    def on_error(self, bus, message):
        print(message.parse_error())
        self.quit()
    
    def quit(self):
        self.pipeline.set_state(Gst.State.NULL)
        self.main_loop.quit()
    
    def run(self):
        self.pipeline.set_state(Gst.State.PLAYING)
        self.main_loop.run()
    
    def switch_track(self):
        audio_track = self.pipeline.get_property("current-audio")
        audio_track = 0 if audio_track == 1 else 1
        print("Switching audio track to %d" % audio_track)
        self.pipeline.set_property("current-audio", audio_track)
        
        video_track = self.pipeline.get_property("current-video")
        video_track = 0 if video_track == 1 else 1
        print("Switching video track to %d" % video_track)
        self.pipeline.set_property("current-video", video_track)
        
        if self.seek:
            print("Seeking to current time")
            _, time = self.pipeline.query_position(Gst.Format.TIME)
            self.pipeline.seek_simple(Gst.Format.TIME, Gst.SeekFlags.FLUSH, time)
        return True

if len(sys.argv) < 2:
    print("Usage: %s uri [--seek]" % (sys.argv[0]))
    sys.exit(1)
else:
    Example(sys.argv[1], len(sys.argv) > 2 and sys.argv[2] == "--seek").run()
