#include "script/common.lua"

HACK_TIME = 1.5

JOINTED_STATIC = 1
JOINTED_DYNAMIC = 2

function init()
	target = FindBody()
	shape = FindShape()
	joint = FindJoint()
	snd = LoadLoop("transmission.ogg")

	local s = GetJointOtherShape(joint, shape)
	if IsBodyDynamic(GetShapeBody(s)) then
		type = JOINTED_DYNAMIC
		initialMass = GetBodyMass(GetShapeBody(s))
	else
		type = JOINTED_STATIC
	end

	hackTime = 0
	done = false
end

function tick(dt)
	if GetBool("level.alarmdisabled") then
		RemoveTag(target, "interact")
		SetTag(target, "target", "disabled")
		SetShapeEmissiveScale(shape, 0)
		done = true
	end

	if not done then
		if GetPlayerInteractBody() == target and InputDown("interact") then
			hackTime = math.min(HACK_TIME, hackTime + dt)
			PlayLoop(snd, GetBodyTransform(target).pos)
			if hackTime == HACK_TIME then
				SetTag(target, "hacked")
				SetTag(target, "target", "cleared")
				RemoveTag(target, "interact")
				SetShapeEmissiveScale(shape, 0)
				done = true
			end
		else
			hackTime = 0
		end

		triggerAlarm = false
		if type == JOINTED_STATIC then
			if IsJointBroken(joint) then
				triggerAlarm = true
			else
				local s = GetJointOtherShape(joint, shape)
				if IsBodyDynamic(GetShapeBody(s)) then
					triggerAlarm = true
				end
			end
		else
			if IsJointBroken(joint) then
				triggerAlarm = true
			else
				local s = GetJointOtherShape(joint, shape)
				local currentMass = GetBodyMass(GetShapeBody(s))
				if currentMass < 0.5 * initialMass then
					triggerAlarm = true
				end
			end
		end
		if triggerAlarm and not alreadyTriggered then
			SetBool("level.alarm", true)
			alreadyTriggered = true
		end
	end
end

function draw()
	if not done and hackTime > 0 then
		UiPush()
			UiTranslate(UiCenter()-100, UiHeight()-220)
			progressBar(200, 20, hackTime/HACK_TIME)
			UiTranslate(100, -10)
			UiAlign("center")
			UiFont("bold.ttf", 24)
			UiText("Âëïòð")
		UiPop()
	end
end
