#!/usr/bin/env python
import easyevent

class EOSListener(easyevent.User):
    def __init__(self):
        easyevent.User.__init__(self)
        self.register_event("eos")

    def evt_eos(self, event):
        import sys
        sys.exit()

if __name__ == '__main__':
    import logging, sys

    logging.basicConfig(
        level=getattr(logging, "INFO"),
        format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s',
        stream=sys.stderr
    )

    def parse_argv(args):
        cmd = ""
        for n in range(1, len(args)):
            cmd+="%s " %args[n]
        return cmd

    from sys import argv
    if len(argv) <= 1:
        print("No gst-launch syntax detected, using built-in example")
        gst_string = None
    else:
        gst_string = parse_argv (argv)

    max_time_ms = 2000
    queue_params = "max-size-buffers=0 max-size-bytes=0 max-size-time=%s" %(max_time_ms*1000000)

    if gst_string is None:
        width, height = 720, 576
        width, height = 1024, 768

        input_caps = "video/x-raw-yuv, format=(fourcc)YUY2, width=(int)%s, height=(int)%s, framerate=(fraction)30/1, pixel-aspect-ratio=(fraction)1/1" %(width, height)
        gst_string = "videotestsrc is-live=True ! %s  ! videorate ! queue leaky=2 ! ffmpegcolorspace ! queue ! theoraenc ! queue ! theoradec  ! queue ! ffmpegcolorspace ! queue ! ximagesink max-lateness=-1" %(input_caps)

    pipeline_desc = gst_string.replace("queue", "progressreport update-freq=1 silent=true ! queue %s" %queue_params)
    from gstmanager.gstmanager import PipelineManager

    pipelinel = PipelineManager(pipeline_desc)
    e = EOSListener()

    import gobject
    gobject.timeout_add(2000, pipelinel.run)


    from clutter import Stage
    s = Stage()
    s.set_size(1024, 768)

    from viz import PipelineViz
    v = PipelineViz(pipelinel, s)

    s.add(v)
    s.show_all()
    import gtk
    gtk.main()
