#!/usr/bin/env python3
import sys
from threading import Thread
import time
import csv 
import gi

gi.require_version("Gst", "1.0")

from gi.repository import Gst, GLib

class theratRTPClientVP8:
    def __init__(self):
        streamStart = False
        t = time.localtime()
        FPS_fileName = "FPScsv/" + time.strftime("%H_%M_%S", t) + ".csv"
        print("file name:", FPS_fileName)




        def fps_measurements_callback (fpsdisplaysink, fps, droprate, avgfps, udata):
            #python callback for the 'fps-measurements' signal
            #print("FPS Function")
            global streamStart
            streamStart = True
            f=open(FPS_fileName, "a")
            writer = csv.writer(f)
            writer.writerow([round(fps, 2)])
            f.close

        x=0
        Gst.init(sys.argv[1:])
        #Gst.debug_set_active(True)
        #Gst.debug_set_default_threshold(3)

        #main_loop = GLib.MainLoop()
        main_loop = GLib.MainLoop.new(None, False)
        thread = Thread(target=main_loop.run)
        thread.daemon = True
        thread.start()
        print("thread.start")


        # Create the empty pipeline
        pipeline = Gst.Pipeline.new("test-pipeline")


        # Create the Source
        source = Gst.ElementFactory.make("udpsrc", "source")
        pipeline.add(source)
        source.props.port=5000
        source.props.caps=Gst.Caps.from_string("application/x-rtp, media=(string)video, encoding-name=(string)VP8")

        # Create the Caps1
        # caps1 = Gst.Caps.from_string("video/x-raw,width=320,height=240")
        # capsfilter1 = Gst.ElementFactory.make("capsfilter", "capsfilter1")
        # capsfilter1.set_property("caps", caps1)
        # pipeline.add(capsfilter1)
        # source.link(capsfilter1)

        # Create the rtpjitterbuffer
        rtpjitterbuffer = Gst.ElementFactory.make("rtpjitterbuffer", "rtpjitterbuffer")
        rtpjitterbuffer.set_property("mode", 1)
        rtpjitterbuffer.set_property("latency", 0)
        pipeline.add(rtpjitterbuffer)
        source.link(rtpjitterbuffer)

        # Create the rtpdpay
        rtpdpay = Gst.ElementFactory.make("rtpvp8depay", "rtpdpay")
        pipeline.add(rtpdpay)
        rtpjitterbuffer.link(rtpdpay)

        # Create the decoder
        decoder = Gst.ElementFactory.make ("avdec_vp8", "decoder")
        pipeline.add(decoder)
        rtpdpay.link(decoder)

        # Create the Convert
        convert = Gst.ElementFactory.make ("videoconvert", "convert")
        pipeline.add(convert)
        decoder.link(convert)


        # Create the textoverlay
        filtery = Gst.ElementFactory.make ("textoverlay", "filtery")
        pipeline.add(filtery)
        convert.link(filtery)
        filtery.props.font_desc="Sans, 32"
        filtery.props.valignment="bottom"

        # Create the videoscale
        videoscale = Gst.ElementFactory.make ("videoscale", "videoscale")
        pipeline.add(videoscale)
        filtery.link(videoscale)


        # Create the sink
        sink = Gst.ElementFactory.make("fpsdisplaysink", "sink")
        sink.set_property("sync", 0)
        sink.set_property("fps-update-interval", 250)
        sink.set_property("signal-fps-measurements", 1)

        pipeline.add(sink)
        videoscale.link(sink)



        # Modify the source's properties
        #asource.props.pattern = 2
        # Can alternatively be done using `source.set_property("pattern",0)`
        # or using `Gst.util_set_object_arg(source, "pattern", 0)`

        pipeline.get_by_name("sink").connect("fps-measurements", fps_measurements_callback, None)

        pipeline.set_state(Gst.State.PLAYING)

        delay=5
        delayCount = round(time.time())+delay
        startTime = round(time.time())

        try:
            while True:
                time.sleep(0.01)
                
                filtery.props.text=str(round(time.time_ns() / 1000000))

                if streamStart == False:
                    startTime = round(time.time())
                if (delayCount <= round(time.time())and(streamStart)):
                    delayCount = round(time.time())+delay

                    jstats = rtpjitterbuffer.get_property('stats')
                    print("=======================")
                    print("file name:", FPS_fileName)
                    print("Pipeline time:", (round(time.time())-startTime), "s")
                    print("the number of packets pushed out: ", jstats.get_value("num-pushed"), " lost:", jstats.get_value("num-lost"))
                    #print("the number of packets considered lost.: ", jstats.get_value("num-lost"))
                    print("the number of packets arriving too late: ", jstats.get_value("num-late"), " duplicate:", jstats.get_value("num-duplicates"))
                    #print("the number of duplicate packets: ", jstats.get_value("num-duplicates"))
                    #print("the average jitter in nanoseconds: ", jstats.get_value("avg-jitter"))
                    #print("The percent of the jitterbuffer", rtpjitterbuffer.get_property('percent'))
                    print("FPS message:", sink.get_property('last-message'))

        except KeyboardInterrupt:
            pass

        pipeline.set_state(Gst.State.NULL)
        main_loop.quit()
        #thread.exit()
        thread.join()