#!/usr/bin/env python
# -*- coding: UTF-8 -*-

import sys
import urllib

from gi.repository import GLib
from gi.repository import GObject
from gi.repository import Gst
from gi.repository import Gtk

class Player(Gtk.Window):
    def __init__(self, uri):
        super(Player, self).__init__()

        self.set_title("Player")
        self.connect("destroy", self.quit)

        self.play_button = Gtk.Button.new_from_stock("gtk-media-play")
        self.play_button.connect("clicked", self.start_stop)
        self.add(self.play_button)

        self.uri = "file://" + urllib.quote(uri)

        self.playbin2 = Gst.ElementFactory.make("playbin2", "playbin2")
        self.playbin2.set_property("uri", self.uri)
        self.playbin2.set_property("message-forward", True)
        self.playbin2.connect("about-to-finish", self.on_about_to_finish)

        self.bus = self.playbin2.get_bus()
        self.bus.add_signal_watch()
        self.bus.enable_sync_message_emission()
        self.bus.connect("message", self.on_message)
        self.bus.connect("sync-message", self.on_sync_message)

    def on_about_to_finish(self, playbin):
        self.play_button.set_label("gtk-media-play")

    def on_message(self, bus, message):
        print "GstMessage:", message

    def on_sync_message(self, bus, message):
        print "GstMessage (sync):", message

    def quit(self, widget):
        self.playbin2.set_state(Gst.State.NULL)
        Gtk.main_quit()

    def start_stop(self, button):
        if self.play_button.get_label() == "gtk-media-play":
            self.play_button.set_label("gtk-media-pause")
            self.playbin2.set_state(Gst.State.PLAYING)
        else:
            self.play_button.set_label("gtk-media-play")
            self.playbin2.set_state(Gst.State.PAUSED)

if __name__ == "__main__":
    if len(sys.argv) == 2:
        GObject.threads_init()
        Gst.init(sys.argv)
        PLAYER = Player(sys.argv[1])
        PLAYER.show_all()
        Gtk.main()
    else:
        sys.exit("No file specified.")

