#!/usr/bin/python
import socket
import _thread
import time
import json
from padra import padra
import threading

LenFunc = 4

padra = padra(LenFunc)
NumberOfOracles = 3
listOfAll = []
def broadcast():
    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    msg = bytes("Message: ",'utf-8')
    sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
    sock.sendto(msg, ("255.255.255.255", 6666))
    while 1:
        m = sock.recvfrom(1024)
        listOfAll.append(((m[1][0]),str(int(m[0]))))
        print(listOfAll)


    

connectedOracles = []
def connection():
    while len(listOfAll)<NumberOfOracles: pass
    for _ in listOfAll: 
        if len(connectedOracles) < NumberOfOracles:
            o = oracle(None,None,None,None,"127.0.0.1",int(_[1]))
            o.start()
            connectedOracles.append(o)
    print(connectedOracles)
    time.sleep(2)
    print(connectedOracles)
    padra.xor(connectedOracles,"11111111111111111111111111223344",
    "11111111111111111111111111223341")



class oracle(threading.Thread):

    def __init__(self, group, target, name,
                 verbose,HOST,PORT):

        super(oracle,self).__init__(group, target, 
			              name, verbose)
        print(HOST,PORT)
        self.port = PORT
        self.Host = HOST
        with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
            s.connect((HOST, PORT))
            data = s.recv(1024)
        ss = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        print(ss)
        ss.connect((HOST,PORT))
        self.s = ss
        self.history = []
        _thread.start_new_thread( self.receive, ())

        def run(self):
            # logging.debug('running')
            return

# 4 char = len of data +  data
    def send(self,Message):
        Message=bytes(Message,'utf-8')
        self.s.sendall(Message)
        self.history.append(("send",Message))
        print("Send",Message)

    def receive(self):
        while True:
            data = self.s.recv(1024)
            if not len:
                break 
            self.history.append(("receive",data))
            print("receive",data)



try:
    _thread.start_new_thread( broadcast, ())
    _thread.start_new_thread( connection, ())
except:
   print ("Error: unable to start thread")
while 1:
    pass