import zmq
import msgpack

class Capture:
    def __init__(self, ip="localhost", port=50020):
        # Setup PupilCore communication
        print('Connecting to "Pupil Capture" ...')
        # REQ socket
        ctx = zmq.Context.instance()
        self.pupil_remote = ctx.socket(zmq.REQ)
        self.pupil_remote.connect(f"tcp://{ip}:{port}")
        # SUB socket
        self.pupil_remote.send_string("PUB_PORT")
        pub_port = self.pupil_remote.recv_string()
        self.pub_socket = zmq.Socket(ctx, zmq.PUB)
        self.pub_socket.connect(f"tcp://{ip}:{pub_port}")
        print("Connected!")
        # time.sleep(2)
        # Start and configure cameras
        notification = {"subject": "eye_process.should_start.0", "eye_id": 0, "args": {}}
        print("Start eye process 0:", self.notify_pupil_remote(notification))
        notification = {"subject": "eye_process.should_start.1", "eye_id": 1, "args": {}}
        print("Start eye process 1:", self.notify_pupil_remote(notification))
        # time.sleep(1)
        notification = {
            "topic": "notify.start_eye_plugin",
            "subject": "start_eye_plugin",
            "target": "eye0",
            "name": "UVC_Source",
            "args": {
                "frame_size": (400, 400),
                "frame_rate": 120,
                "name": "Pupil Cam2 ID0",
                "exposure_mode": "auto",
            },
        }
        print("Configure eye process 1:", self.notify_pupil_remote(notification))
        notification = {
            "topic": "notify.start_eye_plugin",
            "subject": "start_eye_plugin",
            "target": "eye1",
            "name": "UVC_Source",
            "args": {
                "frame_size": (400, 400),
                "frame_rate": 120,
                "name": "Pupil Cam2 ID1",
                "exposure_mode": "auto",
            },
        }
        print("Configure eye process 1:", self.notify_pupil_remote(notification))

    def notify_pupil_remote(self, notification):
        self.pupil_remote.send_string(f"notify.{notification['subject']}", flags=zmq.SNDMORE)
        self.pupil_remote.send(msgpack.dumps(notification))
        return self.pupil_remote.recv_string()