import socket
import struct
import time
import threading
import random
import time
import numpy as np
import argparse
import signal

parser = argparse.ArgumentParser(description='Mininet demo')


packet_holder = [None] * 11
ingress_time = {}
stop_thread = False
runtime = 10

def receive(i):
    global stop_thread, packet_holder
    CLIENT_IP = "0.0.0.0"
    port = 10000 + i
    print i
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    s.bind((CLIENT_IP, port))
    print("listening to {} at port {}".format(CLIENT_IP, port))
    run_status = {}
    packet_holder[i] = []
    while True:
        if stop_thread:
            break
        packet, addr = s.recvfrom(1024)
        packet_holder[i].append((packet, time.time()   ))
        print("packet received : ", packet, addr)
        # print "r", "{0:f}".format((time.time() * 1000)), "{0:f}".format(ingress_time[exec_id])



def printStatistics():
    global runtime
    e2e_time = []
    for packetThread in packet_holder:
        for packetTuple in packetThread:
            packet = packetTuple[0]
            base = 0
            chain_id = struct.unpack(">I", packet[base:base + 4])[0]
            base += 4
            exec_id = struct.unpack(">I", packet[base:base + 4])[0]
            print "print stat : ",packetTuple[1]
            # ,ingress_time[exec_id]
            # print "e2e time : ",(packetTuple[1] - ingress_time[exec_id])* 1000
            # e2e_time.append((packetTuple[1] - ingress_time[exec_id])* 1000)

    # data = np.array(e2e_time, dtype=float)
    # p50 = np.percentile(data, 50)
    # p95 = np.percentile(data, 95)
    # p99 = np.percentile(data, 99)
    # mean = np.mean(data)
    # print("mean \t p50 \t p95 \t p99")
    # print(mean, p50, p95, p99)
    print("rps", len(e2e_time) / runtime, len(ingress_time))
    return 0

ri = []
for i in range(0, 11):
    r = threading.Thread(name="receive", target=receive, args=[i])
    r.daemon = True
    r.start()
    ri.append(r)


def signal_handler(sig, frame):
    global stop_thread
    print "sigint"
    stop_thread = True

print "here"

time.sleep(15)


printStatistics()

