
from connection.broadcast import BroadcastClient
from connection.socket import SocketClient
import time
import config as cfg 
from .userParser import UserParser


class User():
    def __init__(self,data, server, broadcast, broadcastPort):
        print("user")
        self.onlineOracles = []
        self.id = "PADRA"
        self.parser = UserParser(self) 
        self.b = BroadcastClient(broadcast=broadcast,
        broadcastPort=broadcastPort,parser=self.parser,id=self.id)

    def run(self):
        self.b.send(self.parser.requestOracleBroadcast(self.id),self.b.addr)
        
        while(len(self.onlineOracles) < cfg.numberOfOracles):
            print("\tWe need min  ",cfg.numberOfOracles," Oracles. Waiting for mor Oracle. we have now ",len(self.onlineOracles)," online Oracles")
            time.sleep(.5)

        print("\33[31m now we have min ",cfg.numberOfOracles,"Oracles. List of All Online Oracles ->\n",self.onlineOracles,"\n\033[0m")

        worker = []
        
        # Socket creation
        for i in range(cfg.numberOfOracles):
            worker.append(SocketClient("127.0.0.1",int(self.onlineOracles[i][1]),self.parser,None))
        
        #  send rule to each oracle
        for i in range(cfg.numberOfOracles):
            data = self.parser.socketConnecting(i)
            worker[i].id = i
            worker[i].send(data)


        time.sleep(1)

        worker[0].send(self.parser.oracleInitialConnector("www.google.com",worker[1].Host,worker[2].Host))
        worker[1].send(self.parser.oracleInitialCryptor((worker[0].Host,worker[0].port+1),"www.google.com"))
        worker[2].send(self.parser.oracleInitialBearer((worker[0].Host,worker[0].port+1),"Masalan ina data hastand"))

