:NAME door_security_trigger


:PARAM float32 time_since_seen_trigger

:VAR float32 last_immediate_time

-- ------------------- constants ------------------- 

--local vectorlib = require "scripts/vector_math"

k_default_time_since_seen= 5

-- ------------------- initialization ------------------- 


function param_initialize(p)
	p.time_since_seen_trigger = k_default_time_since_seen
end

function var_initialize(v)
	v.last_immediate_time = -1000
end

-- ------------------- component ------------------- 

function attach(object)
	-- set it open
	local door_script= object._c.door
	if (door_script) then
		-- remember, 1 = open
		door_script.position = 1
		door_script.desired_position = 1
		door_script.speed = 0
		door_script.opening= true
		door_script.closing= false
	end
end

function update(object)

	-- test
	local door_script= object._c.door
	if (door_script) then
	
		local ws = world_state_get()
		local time= ws.time.time
		local iterator = ws.component_cache.component_target.iterator_get()
		local immediate= false
		local desired_position= 1		-- I want to be open
		
		while (true) do
			local target_component= iterator.next()
			if (target_component) then
				local target= target_component.target_handle
				if (target and target.is_targetable() and (target.is_immediate() or target.is_making_sound())) then
					immediate= true
				end
			else
				break
			end		
		end

		if (immediate) then
			var.last_immediate_time= time
		end
		
		if ((time - var.last_immediate_time) < param.time_since_seen_trigger) then
			-- the player was seen recently. CLOSE.
			desired_position= 0
		end

		door_script.desired_position= desired_position
	end	
end

component_register(attach, update, nil, nil)
