import time
import zmq
import socket


class TCPClient:
    def __init__(self):
        time.sleep(20)
        self.context = zmq.Context()
        self.sock = self.context.socket(zmq.REQ)
        self.sock.setsockopt(zmq.RCVTIMEO, 300)
        self.sock.setsockopt(zmq.SNDTIMEO, 300)
        self.sock.setsockopt(zmq.LINGER, 300)
        self.sock.connect("tcp://server:5555")
        self.log = open('/app/logs/{}-{}.txt'.format(int(time.time()), socket.gethostname()), 'w+')
        self.commands = {
            "calculate": self.calculate,
            "stop": self.stop
        }
        self.register()
        self.handle()

    def __del__(self):
        self.log.close()

    def stop(self, request):
        exit(0)

    def calculate(self, response):
        s = 0
        for i in range(len(response['arr1'])):
            s += response['arr1'][i] * response['arr2'][i]

        result = {
            "command": "task_done",
            "index": response['index'],
            'client_name': socket.gethostname(),
            "value": s,
        }
        return result

    def register(self):
        request = {"command": "register", 'client_name': socket.gethostname()}
        try:
            self.sock.send_json(request)
            response = self.sock.recv_json()
        except:
            self.log.write("Server goes offline before client tries connect to. Exiting... ")
            exit(0)

        print(request, response)
        if response['success']:
            return True
        else:
            print("AAAA")
            exit(1)

    def handle(self):
        while True:
            request = {"command": "get_task", 'client_name': socket.gethostname()}
            self.sock.send_json(request)
            response = self.sock.recv_json()
            self.log.write(str(response) + '\n')
            command = response['command']
            result = self.commands[command](response)
            self.sock.send_json(result)
            self.log.write(str(self.sock.recv_json()) + '\n')


if __name__ == "__main__":
    client = TCPClient()
