
import socket
import threading
        
import config as cfg

LenFunc = cfg.LenFunc
class Broadcast():
    def __init__(self,  parser, socket,child):
        """ ,broadcast """ # TODO Broadcast
        self.socket = socket
        self.parser = parser
        self.child = child
        t1 = threading.Thread(target=self.listen)
        t1.start()
        print("Broadcast created")


    def listen(self):
        while True:
            data, addr = self.socket.recvfrom(1024)
            d = self.parser.toJSON(data.decode("utf-8")[LenFunc:])
            print("\033[92m \n \treceive",d," \n\tfrom",addr,"\n\033[0m")
            self.parser.parser(d,addr,self.child)

    def send(self, message, addr):
        self.socket.sendto(bytes(message,'utf-8'), addr )
        print("\033[95m \n \tsended to ",addr,"\n\tdata: ",message,"\n\033[0m")




class BroadcastServer(Broadcast):

    def __init__(self,  broadcastPort, parser,id): 

        """ ,broadcast """ # TODO Broadcast
        self.socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        self.socket.bind(('', broadcastPort)) # TODO Broadcast
        self.id = id
        super().__init__(parser,self.socket,self) 


        
class BroadcastClient(Broadcast):

    def __init__(self,broadcast,  broadcastPort, parser,id): 
        self.addr = (broadcast,broadcastPort)
        self.onlineOracles=[]
        self.id = id
        self.socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
        super().__init__(parser,self.socket,self) 


