#include "script/common.lua"

pMessage = "loc@PMESSAGE_HACKING"
pDuration = 2

closeDoor = nil
motor = nil
soundsource = nil
motorSound = nil
motorStart = nil
motorStop = nil
doortrigger = nil
hackShape = nil
doorHeight = nil
target = nil
progress = nil
hacked = nil
hackSnd = nil
motorOn = nil
ledTimer = nil

function init()
	closeDoor = false
	motor = FindJoint("motor")
	soundsource=FindLocation("soundsource")
	motorSound = LoadLoop("firewall-door-loop.ogg")
	motorStart = LoadSound("firewall-door-start.ogg")
	motorStop = LoadSound("firewall-door-stop.ogg")
	doortrigger = FindTrigger("doortrigger")
	hackShape = FindShape("hack")
	doorHeight = GetFloatParam("doorheight",3.3)
	target = doorHeight
	
	progress = 0
	hacked = false
	hackSnd = LoadLoop("transmission.ogg")
	motorOn = false
	
	ledTimer = 0
end

function tick(dt)

	if not hacked then
		if GetPlayerInteractShape() == hackShape and InputDown("interact") then
			progress = progress + dt
			local t = clamp(progress / 2, 0, 1)
			if t == 1 then
				RemoveTag(hackShape, "interact")
				SetShapeEmissiveScale(hackShape, 0)
				PlaySound(motorStart,GetLocationTransform(soundsource).pos)
				hacked = true
			else
				SetBool("level.hacking", true)
				PlayLoop(hackSnd, GetShapeWorldTransform(hackShape).pos)
				SetShapeEmissiveScale(hackShape, math.sin(ledTimer) > 0.5 and 1 or 0)
			end
		else
			progress = 0
			SetShapeEmissiveScale(hackShape, math.sin(ledTimer) > 0.5 and 1 or 0)
		end
		ledTimer = ledTimer+dt*8
	end
	
	if GetBool("level.espionagealarm") and IsPointInTrigger(doortrigger, GetPlayerPos()) then
		if not closeDoor then
			closeDoor=true
			PlaySound(motorStart,GetLocationTransform(soundsource).pos)
		end
	end
	
	if not hacked or closeDoor then
		target = doorHeight
	else
		target = 0
	end
	
	SetJointMotorTarget(motor, target, 0.5, 3000)
	
	if hacked and (GetJointMovement(motor) < doorHeight-0.05 and GetJointMovement(motor) > 0.05) then
		PlayLoop(motorSound,GetLocationTransform(soundsource).pos)
		motorOn = true
	else
		if motorOn then
			PlaySound(motorStop,GetLocationTransform(soundsource).pos)
			motorOn = false
		end
	end
end


function draw()
	if not hacked and progress > 0 then
		UiPush()
			UiTranslate(UiCenter()-100, UiHeight()-220)
			progressBar(200, 20, progress/2)
			UiTranslate(100, -10)
			UiAlign("center")
			UiFont("bold.ttf", 24)
			UiText(pMessage)
		UiPop()
	end
end
