import json
import socket
import threading

from Classes.System.Network.EventHandler import TCPEventHandler
from Classes.Game.World import World
from Classes.System.Components.InputHandler import InputHandler

class TCPClient:
    def __init__(self, addr: str, port: str, world:World, inputHandler:InputHandler):
        self.addr = addr
        self.port = int(port)
        self.tcpSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.eventHandler = TCPEventHandler(self.tcpSocket)
        self.world = world
        self.inputHandler = inputHandler

        try:
            self.tcpSocket.connect((self.addr, self.port))
        except Exception as e:
            print(f"Error connecting TCP socket: {e}")

        # Starten des Listener-Threads
        self.listen()

    def send(self, message: dict):
        try:
            self.tcpSocket.sendall(json.dumps(message).encode())
        except Exception as e:
            print(f"Error sending TCP data: {e}")

    def receive(self):
        while True:
            try:
                data = self.tcpSocket.recv(1024)
                if data:
                    decoded_data = json.loads(data.decode())
                    self.eventHandler.handleEvents(decoded_data, self.inputHandler, self.world)
            except Exception as e:
                print(f"Error receiving TCP data: {e}")
                break

    def listen(self):
        tcpThread = threading.Thread(target=self.receive)
        tcpThread.daemon = True
        tcpThread.start()