import socket
import threading
import queue
import json


class EventListener:
    def __init__(self, event_server):
        self.event_thread = threading.Thread(target=self.receive_events)
        self.event_thread.daemon = True  # mark thread as daemon -> it terminates automatically when program shuts down
        self.event_queue = queue.Queue()
        self.receiving = False

        # connect to event server
        print(f"connecting to event server on {event_server} ...")
        self.event_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)  # TCP socket

        try:
            self.event_socket.connect(event_server)
            self.event_socket.sendall(f"events\n".encode())

            self.event_socket.settimeout(0.1)
            # check if we receive data from the event server
            response = self.event_socket.recv(1024)
            if 'error' not in str(response):
                print("... connected! -> start listening for events")
                self.event_socket.settimeout(None)
                # if so we start the event thread
                self.event_thread.start()
            else:
                print(f"error: cannot communicate with the event server.\n       The response was: {response}")
        except socket.timeout:
            print(f"error: the event server did not respond.")
        except ConnectionRefusedError:
            print(f"error: could not connect to event server at {event_server}.")

    def send_reply(self, data):
        self.event_socket.sendall(data)

    def receive_events(self):
        self.receiving = True
        while self.receiving:
            received = str(self.event_socket.recv(1024), "utf-8")
            if len(received) > 0:
                events = received.split('\n')
                for event_json in events:
                    if len(event_json) > 0:
                        event = json.loads(event_json)
                        self.event_queue.put(event)
            else:
                self.receiving = False
        print("event server seems to have shut down -> stop listening")
