"""
Receive data from Pupil server broadcast over TCP
Send normalized gaze coordinates via LSL
"""
import zmq
from msgpack import loads
from pylsl import StreamInfo, StreamOutlet
import time

# --- LSL Setup ---
info = StreamInfo('PupilGazeStream', 'Gaze_norm', 2, 120, 'float32', 'pupil12345')
outlet = StreamOutlet(info)

# --- ZMQ Setup ---
context = zmq.Context()
addr = "127.0.0.1"
req_port = "50020"

# Request port to get SUB_PORT
req = context.socket(zmq.REQ)
req.connect(f"tcp://{addr}:{req_port}")
req.send_string("SUB_PORT")
sub_port = req.recv_string()

# Subscribe to the Pupil's SUB_PORT
sub = context.socket(zmq.SUB)
sub.connect(f"tcp://{addr}:{sub_port}")
sub.setsockopt_string(zmq.SUBSCRIBE, "surface")

# Surface name you're interested in
surface_name = "screen"

while True:
    try:
        topic = sub.recv_string()
        msg = sub.recv()
        surfaces = loads(msg, raw=False)

        # Filter surface by name
        if surfaces["name"] != surface_name:
            continue

        gaze_positions = surfaces.get("gaze_on_surfaces", [])
        for gaze_pos in gaze_positions:
            norm_gp_x, norm_gp_y = gaze_pos["norm_pos"]
            #if 0 <= norm_gp_x <= 1 and 0 <= norm_gp_y <= 1:
            print(f"gaze on surface: {surface_name}, normalized coordinates: {norm_gp_x}, {norm_gp_y}")
            outlet.push_sample([norm_gp_x, norm_gp_y])
    except KeyboardInterrupt:
        print("Interrupted by user.")
        break
    except Exception as e:
        print("Error:", e)
        time.sleep(0.1)
