pFadeTime = GetFloatParam("fadetime", 6)
gBridgeVol = 0

fadeTrigger = nil
activateTrigger = nil
wakeUpTrigger = nil
lastRobot = nil
fading = nil
alarmTimer = nil
t = nil

function init()
	fadeTrigger = FindTrigger("musicfade")
	activateTrigger = FindTrigger("activate")
	wakeUpTrigger = FindTrigger("wakeup")
	lastRobot = FindBody("lastrobot", true)
	fading = false
	alarmTimer = 0
	t = 0
end

function tick(dt)
	if GetBool("level.espionagealarm") then
		PlayMusic("factory-hunted.ogg")
		SetValue("gBridgeVol", 0)
	else
		local playerPos = GetPlayerEyeTransform().pos
		fading = fading or IsPointInTrigger(fadeTrigger, playerPos)

		if fading then
			t = t + dt
			if t > pFadeTime then t = pFadeTime end
		end
		local vol = 1.0 - t / pFadeTime
		if vol < 1.0 then
			SetFloat("game.music.volume", vol)
			if vol < 0.5 and gBridgeVol == 0 then
				SetValue("gBridgeVol", 1, "linear", 3)
			end
		end
		PlayMusic("factory-noheist.ogg")

		--Wake up taking a picture close to robot
		if GetBool("level.cameraclick") then
			if IsPointInTrigger(activateTrigger, playerPos) then
				RemoveTag(lastRobot, "sleeping")
			end
		end
		
		--Wake up if player in front of robot
		if IsPointInTrigger(wakeUpTrigger, playerPos) then
			RemoveTag(lastRobot, "sleeping")
		end
		
		if not HasTag(lastRobot, "sleeping") then
			alarmTimer = alarmTimer + dt
		end
		if alarmTimer > 1.5 then
			SetBool("level.espionagealarm", true)
		end
	end
end

function draw()
	if gBridgeVol > 0 then
		UiSoundLoop("bridge.ogg", gBridgeVol * (GetFloat("options.audio.musicvolume")/100.0))
	end
end

