#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""This experiment was created using PsychoPy2 Experiment Builder
If you publish work using this script please cite the relevant PsychoPy publications
  Peirce (2007) Journal of Neuroscience Methods 162:8-1
  Peirce (2009) Frontiers in Neuroinformatics, 2: 10"""

from iViewXAPI import  *            #iViewX library
from numpy import *                   #many different maths functions
from numpy.random import *       #maths randomisation functions
import os                                   #handy system and path functions
from psychopy import core, data, event, visual, gui
import psychopy.log                   #import like this so it doesn't interfere with numpy.log


# ---------------------------------------------
#---- store info about the experiment
# ---------------------------------------------

expName = 'GazeContingent'
expInfo={'participant':'', 'session':'001'}
dlg=gui.DlgFromDict(dictionary=expInfo,title=expName)
if dlg.OK==False: core.quit() #user pressed cancel
expInfo['date']=data.getDateStr()#add a simple timestamp
expInfo['expName']=expName


# ---------------------------------------------
#---- setup files for saving
# ---------------------------------------------

#if not os.path.isdir('data'):
#    os.makedirs('data')#if this fails (e.g. permissions) we will get error
#filename='data/%s_%s' %(expInfo['participant'], expInfo['date'])
#psychopy.log.console.setLevel(psychopy.log.warning)#this outputs to the screen, not a file
#logFile=psychopy.log.LogFile(filename+'.log', level=psychopy.log.EXP)


# ---------------------------------------------
#---- connect to iViewX
# ---------------------------------------------

res = iViewXAPI.iV_SetLogger(c_int(1), c_char_p("iViewXSDK_Python_GazeContingent_Demo.txt"))
res = iViewXAPI.iV_Connect(c_char_p('127.0.0.1'), c_int(4444), c_char_p('127.0.0.1'), c_int(5555))

res = iViewXAPI.iV_GetSystemInfo(byref(systemData))
print "iV_GetSystemInfo: " + str(res)
print "Samplerate: " + str(systemData.samplerate)
print "iViewX Verion: " + str(systemData.iV_MajorVersion) + "." + str(systemData.iV_MinorVersion) + "." + str(systemData.iV_Buildnumber)
print "iViewX API Verion: " + str(systemData.API_MajorVersion) + "." + str(systemData.API_MinorVersion) + "." + str(systemData.API_Buildnumber)


# ---------------------------------------------
#---- configure and start calibration
# ---------------------------------------------

calibrationData = CCalibration(5, 1, 0, 0, 1, 20, 239, 1, 10, b"")

res = iViewXAPI.iV_SetupCalibration(byref(calibrationData))
print "iV_SetupCalibration " + str(res)
res = iViewXAPI.iV_Calibrate()
print "iV_Calibrate " + str(res)

iViewXAPI.iV_ShowTrackingMonitor()


# ---------------------------------------------
#---- setup the Window
# ---------------------------------------------

window = visual.Window(size = [1680, 1050],
    pos = [0, 0],
    units = u'pix',
    fullscr = True,
    screen = 0,
    allowGUI = False,
    monitor = 'PrimaryMonitor',
    color = [239, 239, 239])


# ---------------------------------------------
#---- Initialise components for routine: trial
# ---------------------------------------------

trialClock=core.Clock()

sqrVertices = [ [20,20], [20,40], [40,40], [40,20] ]
Shape01 = visual.ShapeStim(win=window,units=u'pix',
    lineRGB=[0,0,0],
    lineWidth=3.0, #in pixels
    fillRGB=[0.0, 0.0, 0.0],
    vertices=sqrVertices,
    closeShape=True,
    pos= [0,0],
    interpolate=True,
    opacity=1.0)


# ---------------------------------------------
#---- run the trial
# ---------------------------------------------
size = 10.0

while True:
    #update gaze data sample
    res = iViewXAPI.iV_GetSample(byref(sampleData))
    if res == 1:
        #print "Gaze Data - Timestamp " + str(sampleData.timestamp) + " Gaze " + str(sampleData.leftEye.gazeX) + " " + str(sampleData.leftEye.gazeY) + " " + str(res)

        Shape01.setFillColor([0.0, 0.0, 0.0])
        sampleData.leftEye.gazeX = sampleData.leftEye.gazeX - 640
        sampleData.leftEye.gazeY = -1 * (sampleData.leftEye.gazeY - 512)
        Shape01.setPos([sampleData.leftEye.gazeX - size, sampleData.leftEye.gazeY - size])
        Shape01.draw()

    res = iViewXAPI.iV_GetEvent(byref(eventData))
    #if res == 1:
        #print "Event: " + str(eventData.positionX) + " " + str(eventData.positionY) + " " + str(res)

    #refresh the screen
    window.flip()

    #check for quit (the [Esc] key)
    if event.getKeys(["escape"]):
        event.clearEvents()
        core.quit()

    #clear event
    event.clearEvents()



# ---------------------------------------------
#---- stop recording and disconnect from iViewX
# ---------------------------------------------

res = iViewXAPI.iV_Disconnect()


#end of this routine
window.close()
core.quit()
