import socket
import struct
import time
import thread
import argparse

NC_PORT = 30041
REPLY_PORT = 9000
SERVER_IP = "192.168.2.2"

parser = argparse.ArgumentParser(description='Mininet demo')
parser.add_argument('--client-port', help='Port of the client',
                    type=int, action="store", required=False)

parser.add_argument('--reply-port', help='Port to reply to',
                    type=int, action="store", required=False)

parser.add_argument('--r', help='Port to reply to',
                    type=int, action="store", required=False)


args = parser.parse_args()

toReply = True if args.r else False
NC_PORT = args.client_port if args.client_port else NC_PORT
REPLY_PORT = args.reply_port if args.reply_port else REPLY_PORT
# CLIENT_IP = "192.168.0.105"
run_status = {}
len_key = 16
counter = 0
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.bind(("0.0.0.0", NC_PORT))
print REPLY_PORT
while True:
    packet, addr = s.recvfrom(1024)
    # print packet

    print "packet : ",packet
    counter = counter + 1
    base = 0
    chain_id = struct.unpack(">I", packet[base:base + 4])[0]
    base += 4
    exec_id = struct.unpack(">I", packet[base:base + 4])[0]
    base += 4
    function_id = struct.unpack(">I", packet[base:base + 4])[0]
    base += 4
    data = struct.unpack(">I", packet[base:base + 4])[0]
    base += 4
    function_count = struct.unpack("B", packet[base])[0]

    if exec_id not in run_status:
        run_status[exec_id] = set()
    if function_id not in run_status[exec_id]:
        run_status[exec_id].add(function_id)
    # else:
    #     continue
    print chain_id, exec_id, "data=", data, "function_id=", function_id, function_count, 
    data = []
    for i in range(1, 6):
        data.append(int(struct.unpack("B", packet[i+base])[0]))
    print data
    chain_id = struct.pack(">I", chain_id)  # chain_id
    exec_id = struct.pack(">I", exec_id)
    function_id = struct.pack("B", function_id)
    current_state = struct.pack("B", 0)
    packetout = chain_id + exec_id + function_id + packet[9:]
    if toReply:
        s.sendto(packet, (SERVER_IP, REPLY_PORT))
