# -*- coding: utf-8 -*-
'''
Created on Wed Jun 17 15:29:09 2020

@author: engs2242
'''
from time import time, sleep
import threading

import zmq

import stlab
from pl_helpers import detect_light_onset, notify, new_trigger

###################################################################
# THIS SCRIPT REQUIRES THE FOLLOWING SETTINGS IN PUPIL CAPTURE... #
# 1. Resolution (640, 480) for all cameras                        #  
# 2. Frame rate 120 for all cameras                               #
# 3. Auto Exposure mode - Manual Exposure - all cameras           # 
# 4. Absolute exposure time 120 - both cameras                    #
# 5. Frame publisher format - BGR                                 #
###################################################################

# make 1s pulse
stlab.make_video_pulse([2000]*10, 1000, '1s_max_pulse')

# set up zmq context and remote helper for tracker
context = zmq.Context()
address = '127.0.0.1'  # remote ip or localhost
request_port = '50020'  # same as in the pupil remote gui
pupil_remote = zmq.Socket(context, zmq.REQ)
pupil_remote.connect('tcp://{}:{}'.format(address, request_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()

pub_socket = zmq.Socket(context, zmq.PUB)
pub_socket.connect('tcp://{}:{}'.format(address, pub_port))

pupil_remote.send_string('T {}'.format(time()))
print(pupil_remote.recv_string())

subscriber = context.socket(zmq.SUB)
subscriber.connect('tcp://{}:{}'.format(address, sub_port))

# subscribe only to frame.world
subscriber.setsockopt_string(zmq.SUBSCRIBE, 'frame.world')
    
# Config Pupil Capture
#plh.notify(pupil_remote, {'subject':'start_plugin','name':'UVC_Source','args':{'frame_size': (640, 480),'frame_rate': 60,'name':'Pupil Cam1 ID2','exposure_mode':'manual'}})
notify(pupil_remote, {'subject':'start_plugin', 'name':'Annotation_Capture'})
notify(pupil_remote, {'subject':'frame_publishing.set_format', 'format':'bgr'})

# setup stlab
d = stlab.Device(username='admin', identity=1, password='83e47941d9e930f6')
d.load_video_file('1s_max_pulse.dsf')

label = 'LIGHT_ON'
light_on_trigger = new_trigger(label, duration=1.)
threshold = 20

# start recording
pupil_remote.send_string('R plr_integration_tests')
pupil_remote.recv_string()

sleep(5.)  

for i in range(6):
    sleep(5.)  
    t = threading.Thread(target=detect_light_onset, args=(
        subscriber, pub_socket, light_on_trigger, threshold))
    t.start()
    sleep(.5)
    d.play_video_file()
    sleep(20.)  
    
sleep(5.)   
pupil_remote.send_string('r')
pupil_remote.recv_string()

