#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
This file is called template.py. It is a fully functional dummy experiment.
You can use this file as a start for programming your PsychoPy experiment.
The file template_stimuli.csv contains the following:
number;stimulus
0;"Graham Chapman"
1;"Eric Idle"
2;"Terry Gilliam"
3;"Terry Jones"
4;"John Cleese"
5;"Michael Palin"

"""


from psychopy import core, clock, visual, event
import csv, random
import my # import my own functions

## Setup Section
win = visual.Window([800,600], fullscr=False, monitor="testMonitor", units='cm')

# read stimuli file
trials = my.getStimulusInputFile('template_stimuli.csv')
numberColumn = 0     #number = trials[trialNumber][numberColumn]
nameColumn = 1       #name = trials[trialNumber][nameColumn]


# turn the text strings into stimuli
textStimuli = []
for trial in trials:
    # append this stimulus to the list of prepared stimuli
    textStimuli.append(visual.TextStim(win, text=trial[nameColumn])) 
    #imageStimuli.append(visual.ImageStim(win=window, size=[0.5,0.5], image="image/"+row[0]))
    #soundStimuli.append(visual.ImageStim(win=window, size=[0.5,0.5], image="image/"+row[0]))

#fixation cross
fixation = visual.ShapeStim(win, 
	vertices=((0, -0.5), (0, 0.5), (0,0), (-0.5,0), (0.5, 0)),
	lineWidth=5,
	closeShape=False,
	lineColor='white'
)

# open data output file
ppn = my.getString(win, "Please enter a participant number:")
datafile = my.openDataFile(ppn)
# connect it with a csv writer
writer = csv.writer(datafile, delimiter=";")
# create output file header
writer.writerow([
	"number", 
	"name", 
	"buttonPressed",  
	"fixationTime", 
	"textTime", 
	"responseTime",
	])

 
## Experiment Section
# show welcome screen
my.getCharacter(win, "Welcome, press any key to start")
startTime = clock.getTime() # clock is in seconds

for i in range(len(trials)):
	trial = trials[i]
	
	# present fixation
	fixation.draw()
	win.flip()
	fixationTime = clock.getTime()
	core.wait(0.980) # note how the real time will be very close to a multiple of the refresh time
	
	# present stimulus text and wait a maximum of 2 second for a response
	textStimuli[i].draw()
	win.flip()
	textTime = clock.getTime()
	key = event.waitKeys(2.000)
	responseTime = clock.getTime()
	print("text: {}, key: {}, {}".format( trial[nameColumn], key, responseTime-textTime) )
	
	# black screen for 1000 ms
	win.flip()
	core.wait(1.000)
	
	# write result to data file
	if key==None:
		key=[]
		key.append("no key")
		
	writer.writerow([
		trial[numberColumn], 
		trial[nameColumn], 
		key[0],  
		"{:.3f}".format(fixationTime - startTime), 
		"{:.3f}".format(textTime - startTime), 
		"{:.3f}".format(responseTime - textTime),
		])
	
	if key[0]=='escape':
		break
datafile.close()

# show goodbye screen
my.showText(win, "Thank you for participating")
core.wait(1.000)

## Closing Section
win.close()
core.quit()
