import json
import config as cfg
from connection.socketClient import Socket
LenFunc = cfg.LenFunc



class Worker():
    def __init__(self,child,parent):
        self.child          = child
        self.parent         = parent
        self.bearer         = None
        self.crypter        = None
        self.connector      = None
        self.connectorIP    = None
        self.connectorPort  = None
        self.id             = None
        self.server         = None
        self.key_exchange   = None

    def toJSON(self, data):
        return json.loads(data)

    def toSTRING(self, data):
        return json.dumps(data)

    def toSEND(self, data):
        j = json.dumps(data)
        l = LenFunc - len(str(len(j)))
        self.send("0000"[0:l]+str(len(j))+j)


    def send(self,Message):
        Message=bytes(Message,'utf-8')
        self.connector.sendall(Message)
        print("Send",Message)

    def receive(self):
        while True:
            len = self.connector.recv(LenFunc)
            if not len:
                break
            data = self.connector.recv(int(len))
            print("receive",data)
            self.parser(data)

    def parser(self,data,conn):
        data = self.toJSON(data)
        print(data)

        if    (data["type"]       ==      "init"                ):
            self.id             = data["id"]
            self.connectorIP    = data["connectorIP"]
            self.connectorPort  = data["connectorPort"]
            self.server  = data["server"]
            self.child.start(data)
        elif  (data["type"]       ==      "oracleInit"          ):
            if data["oracle"] == "Cryptor":
                self.crypter = conn
            elif data["oracle"] == "Bearer":
                self.bearer = conn
            else:
                print("Wrong INITIAL ORACLE")
        elif  (data["type"]       ==      "key_exchange"           ):
            self.key_exchange      = data["key_exchange"]
            self.child.createConnection()


