# -*- coding: utf-8 -*-
"""
Created on Sun Jun 19 21:27:07 2022

@author: User
"""

# =============================================================================
# from pupil_labs.realtime_api.simple import discover_one_device
# 
# # Look for devices. Returns as soon as it has found the first device.
# print("Looking for the next best device...")
# device = discover_one_device(max_search_duration_seconds=10)
# if device is None:
#     print("No device found.")
#     raise SystemExit(-1)
# 
# # device.streaming_start()  # optional, if not called, stream is started on-demand
# 
# try:
#     while True:
#         print(device.receive_gaze_datum())
# except KeyboardInterrupt:
#     pass
# finally:
#     print("Stopping...")
#     # device.streaming_stop()  # optional, if not called, stream is stopped on close
#     device.close()  # explicitly stop auto-update
# =============================================================================

from pythonosc import dispatcher
from pythonosc import osc_server
from pythonosc import udp_client
import zmq
import msgpack
import socket
import argparse

ctx = zmq.Context()
# The REQ talks to Pupil remote and receives the session unique IPC SUB PORT
pupil_remote = ctx.socket(zmq.REQ)

ip = 'localhost'  # If you talk to a different machine use its IP.
port = 50020  # The port defaults to 50020. Set in Pupil Capture GUI.

pupil_remote.connect(f'tcp://{ip}:{port}')

# Request 'SUB_PORT' for reading data
pupil_remote.send_string('SUB_PORT')
sub_port = pupil_remote.recv_string()

# Request 'PUB_PORT' for writing data
pupil_remote.send_string('PUB_PORT')
pub_port = pupil_remote.recv_string()

#...continued from above
# Assumes `sub_port` to be set to the current subscription port
subscriber = ctx.socket(zmq.SUB)
subscriber.connect(f'tcp://{ip}:{sub_port}')
subscriber.subscribe('gaze.')  # receive all gaze messages

parser = argparse.ArgumentParser()
parser.add_argument("--ip", default="127.0.0.1",
                    help="The ip of the OSC server")
parser.add_argument("--port", type=int, default=5005,
                    help="The port the OSC server is listening on")
args = parser.parse_args()

client = udp_client.SimpleUDPClient(args.ip, args.port)

#Unused
#singleeyepack = [0.0, 0.0, 0.0]
#eyepackleft = [0.0, 0.0, 0.0]
#eyepackleft = [0.0, 0.0, 0.0]

while True:
    try:
        topic, payload = subscriber.recv_multipart()
        message = msgpack.loads(payload)
        #print(f"{topic}: {message}")
        #tdmsg = f"{topic}: {message}"
        
        if(message['topic'] == 'gaze.3d.0.'):
            client.send_message("/gaze_normals_3d_lx", message['gaze_normal_3d'][0])
            client.send_message("/gaze_normals_3d_ly", message['gaze_normal_3d'][1])
            client.send_message("/gaze_normals_3d_lz", message['gaze_normal_3d'][2])
            client.send_message("/gaze_point_3d_x", message['gaze_point_3d'][0])
            client.send_message("/gaze_point_3d_y", message['gaze_point_3d'][1])
            client.send_message("/gaze_point_3d_z", message['gaze_point_3d'][2])
        elif(message['topic'] == 'gaze.3d.1.'):
            client.send_message("/gaze_normals_3d_rx", message['gaze_normal_3d'][0])
            client.send_message("/gaze_normals_3d_ry", message['gaze_normal_3d'][1])
            client.send_message("/gaze_normals_3d_rz", message['gaze_normal_3d'][2])
            client.send_message("/gaze_point_3d_x", message['gaze_point_3d'][0])
            client.send_message("/gaze_point_3d_y", message['gaze_point_3d'][1])
            client.send_message("/gaze_point_3d_z", message['gaze_point_3d'][2])
        elif(message['topic'] == 'gaze.3d.01.'):
            client.send_message("/gaze_normals_3d_lx", message['gaze_normals_3d']['0'][0])
            client.send_message("/gaze_normals_3d_ly", message['gaze_normals_3d']['0'][1])
            client.send_message("/gaze_normals_3d_lz", message['gaze_normals_3d']['0'][2])
            client.send_message("/gaze_normals_3d_rx", message['gaze_normals_3d']['1'][0])
            client.send_message("/gaze_normals_3d_ry", message['gaze_normals_3d']['1'][1])
            client.send_message("/gaze_normals_3d_rz", message['gaze_normals_3d']['1'][2])
            client.send_message("/gaze_point_3d_x", message['gaze_point_3d'][0])
            client.send_message("/gaze_point_3d_y", message['gaze_point_3d'][1])
            client.send_message("/gaze_point_3d_z", message['gaze_point_3d'][2])
        
        #These I tried with UDP but failed.
        #eyepack = singleeyepack#(singleeyepack) #+ ' ' + eyepackleft + ' ' + eyepackright)
        
        #split_msg = eyepack.encode()
    
        #sock.sendto(split_msg, (UDP_IP, UDP_PORT))
    except KeyError:
        pass
    except KeyboardInterrupt:								# Ctrl+C
        pass