-- Constants --

EVENT_NULL =          0  -- Nothing
EVENT_NOTE_OFF =      1
EVENT_NOTE_ON =       2
EVENT_VOLUME = 3
EVENT_EFFECT = 4
EVENT_CHANGE_ORDER = 5
EVENT_CHANGE_PATTERN = 6
EVENT_CHANGE_ROW = 7
EVENT_SONG_END = 8

NOTE_NULL = -1
NOTE_OFF = -2
INSTRUMENT_NULL = -1
VOLUME_NULL = -1
TRACK_NULL = -1
COLUMN_NULL = -1
ORDER_NULL = -1
PATTERN_NULL = -1
ROW_NULL = -1
EFFECT_NULL = -1
EFFECT_VALUE_NULL = -1

-- Class(es) --

Event = { timestamp = 0, type = EVENT_NULL, note = NOTE_NULL, instrument =  INSTRUMENT_NULL, volume = VOLUME_NULL, track = TRACK_NULL, column = COLUMN_NULL, effect = EFFECT_NULL, effectValue = 0, row = 0, pattern = 0, order_position = ORDER_NULL}
Event_mt = { __index = Event }

function Event:new(o)
	o = o or {}
	return setmetatable( o, Event_mt )
end


EventDispatcher = {}
EventDispatcher.currentEvent = 1 -- ARRAYS BEGIN IN 1!!!
EventDispatcher.listeners = {}

function EventDispatcher.update(time)
	local index = EventDispatcher.currentEvent
	local event = events_list[index]
	
	if index >= #events_list then
		return true
	end
	
	while event.timestamp <= time do
		--print('EventDispatcher: ', index, 'o', event.order_position, 'r', event.row)
		-- Dispatch the event to the listeners
		for k, eventListener in pairs(EventDispatcher.listeners) do
			if eventListener.type == event.type then
				eventListener.listener:processEvent(event)
			end
		end
		
		-- And let's see what's with the next one!
		-- trace("next event, " .. index)
		index = index + 1
		event = events_list[index]
	end
	EventDispatcher.currentEvent = index
	
	return false
end

function EventDispatcher.addEventListener(listener, type)
	table.insert(EventDispatcher.listeners, { listener = listener, type = type } )
end
