import sys
import json, ast
from RTEInterface import RTEInterface
from kafka import KafkaConsumer

consumer = KafkaConsumer('deployed', 'removeWorker',
                         "request", bootstrap_servers='10.129.6.5:9092')

RTEInterface.Connect('thrift', "10.129.2.201", 20206)
tableId = "ingress::dispatch"
rule_name = "dispatch_to_worker"
# default_rule = True
actions = '''{  "type" : "ingress::dispatch_act",  
    "data" : { "dstAddr" : { "value" : "%s" }, 
    "dstPort" : { "value" : "%d" } } }''' % ("192.168.2.2", 8080)
print actions
# RTEInterface.Tables.AddRule(tableId, rule_name, default_rule, actions)
ruleList = RTEInterface.Tables.ListRules(tableId)
print ruleList

for msg in consumer:
    print msg, msg.topic
    if msg.topic == "deployed":
        msg = msg.value.decode('utf-8')
        # worker = str(msg.value)
        # worker = ast.literal_eval(json.dumps(worker)) 
        worker = json.loads(msg)
        print worker, worker[u'node_id']
        print str(worker[u'node_id']).strip()
        print int(worker[u'portExternal'])
    
        default_rule = False
        actions = '''{  "type" : "ingress::dispatch_act",  
            "data" : { "dstAddr" : { "value" : "%s" }, 
            "dstPort" : { "value" : "%d" } } }''' % (str(worker[u'node_id']).strip(), \
                int(worker[u'portExternal']))
        print actions
        # % (data.param3)
        match = '{ "map_hdr.chain_id" : {  "value" : "0"} } '
        RTEInterface.Tables.AddRule(tableId, rule_name, default_rule, match, actions)
        ruleList = RTEInterface.Tables.ListRules(tableId)
        print ruleList
    
    elif msg.topic == "removeWorker":
        
