:NAME finale

:LOCKED_DOOR c_object*			door
:LOCKED_DOOR float32			delay

:GLOBAL locked_door[]			doors
:GLOBAL float32					last_check_time
:GLOBAL boolean					started


k_door_check_delay= 1

function global_initialize(g)
	g.last_check_time= 0
end

function start()
	local world= world_get()
	local ws= world_state_get()
	local ps= ws.plate_state_get("finale")
	
	local object= ps.objects
	while object do
		local locked_script = object._c.door_locked_trigger
		if (locked_script) then
			local door= global.doors.create()
			if (door) then
				door.door= object
				door.delay= -1
			end
		end
		object= object.plate_object_next
	end
end

function open_all_start()
	local iterator= global.doors.iterator_get()
	while (true) do
		local door= iterator.next()
		if (door) then
			door.delay = 0.25 + 1.25*math.random()
		else
			break
		end
	end
	
	global.started= true
end

function update()

	local ws= world_state_get()
	if (global.started) then

		local dt= ws.time.delta_t()
		local iterator= global.doors.iterator_get()
		local found_locked_door= false
		while (true) do
			local door= iterator.next()
			if (door) then
				if (door.delay > 0) then
					door.delay= door.delay - dt
					if (door.delay <= 0) then
						door.delay= 0
						local lock_script= door.door._c.door_locked_trigger
						lock_script.magic_unlock = true
					else
						found_locked_door= true
					end
				end
			else
				break
			end
		end
		
		if (not found_locked_door) then
			sleep()
		end
	
	else
		local time= ws.time.time
		if ((time - global.last_check_time) > k_door_check_delay) then
			
			local iterator= global.doors.iterator_get()
			while (true) do
				local door= iterator.next()
				if (door) then
					local lock_script= door.door._c.door_locked_trigger
					if (lock_script.is_unlocked) then
						open_all_start()
						break
					end
				else
					break
				end
			end
		end
	end

end

system_register(start, update, nil, nil)
