-- This Lua script generates target stimulations the 1x6 p300-tactile matrix
--
-- Author : Tobias Baumann
-- Date   : 2021-06-09

-- this function is called when the box is initialized
function initialize(box)

	dofile(box:get_config("${Path_Data}") .. "/plugins/stimulation/lua-stimulator-stim-codes.lua")

	math.randomseed(os.time())
	row_base   = _G[box:get_setting(2)]
	col_base   = _G[box:get_setting(3)]
	n_tactilos = box:get_setting(4)
	delay = box:get_setting(5)
	if box:get_setting(6) == 'true' then
		free_spelling = true
	else
		free_spelling = false
	end
end

-- this function is called when the box is uninitialized
function uninitialize(box)
end

-- this function is called once by the box
function process(box)

	-- loop until box:keep_processing() returns zero
	-- cpu will be released with a call to sleep
	-- at the end of the loop
	while box:keep_processing() do

		-- gets current simulated time
		t = box:get_current_time()
		
		-- loops on every received stimulation for a given input
		for stimulation = 1, box:get_stimulation_count(1) do

			-- gets stimulation
			stimulation_id, stimulation_time, stimulation_duration = box:get_stimulation(1, 1)
			
			if not free_spelling then
				if stimulation_id == OVTK_StimulationId_RestStart then

					-- triggers the target
					box:send_stimulation(1, row_base+math.random(1,n_tactilos)-1, t+delay, 0)
					box:send_stimulation(1, col_base, t+delay, 0)

				elseif stimulation_id == OVTK_StimulationId_ExperimentStop then

					-- triggers train stimulation
					box:send_stimulation(1, OVTK_StimulationId_Train, t+delay+1, 0)

				end	
			end
			-- discards it
			box:remove_stimulation(1, 1)

		end

		-- releases cpu
		box:sleep()
	end
end