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

import sys
import urllib

from gi.repository import GLib, GObject, Gst

def get_tags(file_path):
    if not file_path.startswith("file://"):
        file_path = "file://" + file_path

    if not Gst.uri_is_valid(file_path):
        file_path = urllib.quote(file_path)

    pipeline = Gst.Pipeline.new("pipeline")

    uridecodebin = Gst.ElementFactory.make("uridecodebin", "uridecodebin")
    uridecodebin.set_property("uri", file_path)
    pipeline.add(uridecodebin)

    fakesink = Gst.ElementFactory.make("fakesink", "fakesink")
    pipeline.add(fakesink)

    pipeline.set_state(Gst.State.PAUSED)

    tags = {}

    bus = pipeline.get_bus()

    while True:
        msg = bus.pop_filtered(Gst.MessageType.ASYNC_DONE | Gst.MessageType.TAG | Gst.MessageType.ERROR)

        if msg:
            if msg.type != Gst.MessageType.TAG:
                break
            else:
                print("*** Now the script executes gst_message_parse_tag()")
                tag_list = msg.parse_tag()

                for tag in tag_list.keys():
                    if not tag in tags:
                        tags[tag] = tag_list[tag]

    print tags

    pipeline.set_state(Gst.State.NULL)

if __name__ == "__main__":
    if len(sys.argv) != 2:
        sys.exit("Usage: %s /path/to/file" % sys.argv[0])

    GObject.threads_init()
    Gst.init(sys.argv)
    get_tags(sys.argv[1])

