#include "script/common.lua"

pLimit = GetFloatParam("limit", 50)


function getBodyVoxelCount(b)
	local count = 0
	local shapes = GetBodyShapes(b)
	for i=1, #shapes do
		count = count + GetShapeVoxelCount(shapes[i])
	end
	return count
end


function init()
	target = FindBody("target")
	alarmShape = FindShape("alarm")
	
	orgVoxCount = getBodyVoxelCount(target)
	lastVoxCount = orgVoxCount
	percentage = 100
	done = false
	doneTimer = 0
	doneAlpha = 0
	breakTimer = 0
	breakAlpha = 0
end


function tick(dt)
	local t = math.mod(GetTime(), 1.0)
	if GetBool("level.alarm") then
		--Alarm blink
		if t < 0.5 then
			SetShapeEmissiveScale(alarmShape, 1)
		else
			SetShapeEmissiveScale(alarmShape, 0)
		end
	else
		--Regular blink
		if t > 0.9 then
			SetShapeEmissiveScale(alarmShape, 0.5)
		else
			SetShapeEmissiveScale(alarmShape, 0)
		end
	end

	if done then
		doneTimer = doneTimer + dt
		if doneTimer > 2 then
			if doneAlpha == 1 then
				SetValue("doneAlpha", 0.0, "linear", 0.25)
			end
		else
			if doneAlpha == 0 then
				SetValue("doneAlpha", 1.0, "linear", 0.25)
			end
		end
		return
	end

	currentVoxCount = getBodyVoxelCount(target)
	if currentVoxCount < orgVoxCount then
		SetBool("level.alarm", true)
	end
	percentage = currentVoxCount / orgVoxCount * 100

	if percentage < pLimit then
		SetTag(target, "target", "cleared")
		done = true
	end
	
	if currentVoxCount < lastVoxCount then
		breakTimer = 1
		breakAlpha = 1
	end
	lastVoxCount = currentVoxCount
	if breakTimer > 0 then
		breakTimer = breakTimer - dt
		if breakTimer <= 0 then
			SetValue(breakTimer, 0, "linear", 0.25)
		end
	end
end
	
	
function draw()
	local MAX_DIST = 20
	local FADE_DIST = 5
	if not done then
		local x, y, dist = UiWorldToPixel(GetBodyTransform(target).pos)
		if dist > 0 then
			local a = math.clamp((MAX_DIST - dist)/FADE_DIST, 0.0, 1.0)
			a = math.max(a, breakAlpha)
			if a > 0 then
				local life = math.clamp((percentage-pLimit)/(100-pLimit)*100, 0, 100)
				UiColorFilter(1,1,1,a)
				UiTranslate(x, y)
				UiAlign("center middle")
				UiColor(0,0,0, 0.5)
				UiImageBox("ui/common/box-solid-6.png", 250, 80, 6, 6)
				UiWindow(250, 80)
				UiTranslate(125, 25)
				UiColor(1,1,1)
				UiPush()
					UiFont("bold.ttf", 22)
					UiText("Òòõöò¿ñìé ".. math.floor(life) .. "%")
				UiPop()
				UiTranslate(-100, 15)
				progressBar(200, 20, life/100, 0)
			end
		end
	else
		local x, y, dist = UiWorldToPixel(GetBodyTransform(target).pos)
		if dist > 0 and doneAlpha > 0 then
			UiColorFilter(1,1,1,doneAlpha)
			UiTranslate(x, y)
			UiAlign("center middle")
			UiColor(0,0,0, 0.75)
			UiImageBox("ui/common/box-solid-6.png", 150, 40, 6, 6)
			UiWindow(150, 40)
			UiTranslate(75, 20)
			UiColor(1,1,1)
			UiPush()
				UiFont("bold.ttf", 22)
				UiText("Ñãëôùþéñò")
			UiPop()
		end
	end
end

