import tobii_research as tr
import csv
import time

# Initialize the eye tracker
found_eye_tracker = False
eye_tracker = None

# Try to find the eye tracker
while not found_eye_tracker:
    eye_trackers = tr.find_all_eyetrackers()
    if eye_trackers:
        eye_tracker = eye_trackers[0]  # Assuming only one eye tracker is connected
        found_eye_tracker = True
    else:
        print("Eye tracker not found. Retrying in 2 seconds...")
        time.sleep(2)

# Open CSV file for writing
csv_file = open('eye_tracking_data.csv', 'w', newline='')
csv_writer = csv.writer(csv_file)

# Write header
csv_writer.writerow(['Timestamp', 'Left Gaze X', 'Left Gaze Y', 'Right Gaze X', 'Right Gaze Y', 
                     'Left Pupil Dilation', 'Right Pupil Dilation', 'Left Corneal Reflection', 'Right Corneal Reflection'])

# Callback function for gaze data subscription
def gaze_data_callback(gaze_data):
    timestamp = gaze_data['timestamp']
    left_gaze_point = gaze_data['left_gaze_point_on_display_area']
    right_gaze_point = gaze_data['right_gaze_point_on_display_area']
    left_pupil_dilation = gaze_data['left_pupil_diameter']
    right_pupil_dilation = gaze_data['right_pupil_diameter']
    left_corneal_reflection = gaze_data['left_cornear_reflection']
    right_corneal_reflection = gaze_data['right_cornear_reflection']
    
    # Write data to CSV file
    csv_writer.writerow([timestamp, left_gaze_point[0], left_gaze_point[1], 
                         right_gaze_point[0], right_gaze_point[1], 
                         left_pupil_dilation, right_pupil_dilation, 
                         left_corneal_reflection, right_corneal_reflection])
    csv_file.flush()  # Flush the buffer to ensure data is written immediately

# Subscribe to gaze data
eye_tracker.subscribe_to(tr.EYETRACKER_GAZE_DATA, gaze_data_callback, as_dictionary=True)

# Let it run for 60 seconds
time.sleep(60)

# Unsubscribe from gaze data and close connection to the eye tracker
eye_tracker.unsubscribe_from(tr.EYETRACKER_GAZE_DATA, gaze_data_callback)
eye_tracker.disconnect()

# Close CSV file
csv_file.close()
