#include "script/common.lua"
pHighlightPercentage = GetFloatParam("highlight", 0.0)
pTimeLimit = GetFloatParam("timelimit", 120)

pSound = GetStringParam("sound", "escape-boat.ogg")
pAcceleration = GetFloatParam("acceleration", 6)
pMaxSpeed = GetFloatParam("maxspeed", 22)
pFollowCam = GetIntParam("followcam", 1)
pDynamic = GetBoolParam("dynamic", false)
pArrowSize = 2

function init()
	done = false
	
	--The trigger indicates where to count voxels
	local trigger = FindTrigger("demolish2")
	aabbMin, aabbMax = GetTriggerBounds(trigger)

	label = FindLocation("label")
	worldUiY = 0
	screenUiY = 0

	timer = -1

	SetFloat("level.demolish.percentage", 100)
	center = FindBody("center")
	
	percentage = 100

	--Count initial static voxels in aabb
	totalVoxCount = 0
	QueryRequire("static")
	local allShapes = QueryAabbShapes(aabbMin, aabbMax)
	for i=1, #allShapes do
		totalVoxCount = totalVoxCount + GetShapeVoxelCount(allShapes[i])
	end

	timeBeforeWin = 0

	warnTime = 0
	warnPercent = 100
	gracePercent = 1

	fadeToBlackAlpha = 0
	fadeInAlpha = 4

	countdownBeforeFireworks = 26 --goes up to 60
	SetBool("level.demolish.fireworks", false)


	--Escape setup
	local arrow = FindLocation("arrow")
	if arrow ~= 0 then
		arrowSprite = LoadSprite("gfx/arrowdown.png")
		arrowPos = GetLocationTransform(arrow).pos
		arrowPos[2] = arrowPos[2] + pArrowSize/2
	end

	cameraPos = GetLocationTransform(FindLocation("escapecamera")).pos
	body = FindBody("escapevehicle")
	shapes = GetBodyShapes(body)
	for i=1,#shapes do
		SetShapeEmissiveScale(shapes[i], 0.0)
	end
	
	SetTag(body, "nocull")
	SetTag(body, "interact", "Ïöèòûñùö¼")
	transform = GetBodyTransform(body)
	dir = TransformToParentVec(transform, Vec(0, 0, -1))
	sound = LoadSound(pSound)
	speed = 0
	followCam = true
	hatch = FindShape("hatch")

	rested = false
	fadeDone = false
end


function tick(dt)
	local state = GetString("level.state")
	local complete = GetBool("level.complete")

	--Third person win/lose camera
	if state == "win" or state == "fail_alarmtimer" or state == "fail_missiontimer" then
		if followCam then
			t = Transform(cameraPos, QuatLookAt(cameraPos, GetBodyTransform(body).pos))
			if pFollowCam == 0 then
				followCam = false
			end
		end
		SetCameraTransform(t, 90)
	end

	if not fadeDone and rested then
		-- Start fireworks when fade is done
		if fadeToBlackAlpha <= 0 then
			--SetBool("game.disableinput", false)
			fadeDone = true
			SetTag(body, "interact", "Òäéêãö¼")
			
			fireworkTimer = 0
			countdownBeforeFireworks = 70
			SetBool("level.demolish.fireworks",true)

			if state == "" then
				SetFloat("level.timelimit", pTimeLimit + GetFloat("level.missiontime") + GetFloat("options.game.campaign.time"))
			end
		end
		SetBool("hud.disable",true)		
		SetBool("game.disableinput", true)
		return
	end

	if not rested and GetTime() > 5 then 
		--Draw rested arrow
		if arrowSprite then
			local c = GetCameraTransform().pos
			c[2] = arrowPos[2]
			local p = VecCopy(GetBodyTransform(body).pos)
			p[2] = p[2] + math.sin(GetTime()*5)*0.3+3.8
			local t = Transform(p, QuatLookAt(arrowPos, c))
			DrawSprite(arrowSprite, t, pArrowSize, pArrowSize, 1, 1, 1, 1, true, false)
		end
	end

	if state == "" then			
		if GetPlayerInteractBody() == body and not GetBool("level.demolish.fireworks") and not rested then

			DrawBodyOutline(body, 1)
			if InputPressed("interact") then
				rested = true
				fadeInAlpha = 4
				SetValue("fadeInAlpha",0,"linear",0.5)

				fadeToBlackAlpha = 4
				SetValue("fadeToBlackAlpha",0,"linear",4)
				RemoveTag(body, "interact")
				SetBool("level.disablequicksave", true)				
			end
		end
		if complete then
			--Draw escape vehicle arrow
			if arrowSprite then
				local c = GetCameraTransform().pos
				c[2] = arrowPos[2]
				local p = VecCopy(arrowPos)
				p[2] = p[2] + math.sin(GetTime()*5)*0.3+0.3
				local t = Transform(p, QuatLookAt(arrowPos, c))
				DrawSprite(arrowSprite, t, pArrowSize, pArrowSize, 1, 1, 1, 1, true, false)
			end
		end

		if GetPlayerInteractBody() == body then
			if complete then
				DrawBodyOutline(body, 1)
			end
			if InputPressed("interact") then
				if complete then
					SetString("level.state", "win")
				else
					if fadeDone then
						SetString("hud.notification", "Òñãýãïã åãð ñùêñò åºóòïñìö¼ åõé ñéòäûòèìðºé üéïì")
					end
				end
			end
		end
	end

	if done then
		return
	end

	if GetString("level.state") == "" then
		if GetBool("level.demolish.fireworks") then
			PlayMusic("mall-hunted.ogg")
		else
			PlayMusic("mall-destruction-1.ogg")
		end
	end

	local currentVoxCount = 0

	--Count all static voxels in aabb
	QueryRequire("static")
	local allShapes = QueryAabbShapes(aabbMin, aabbMax)
	for i=1, #allShapes do
		currentVoxCount = currentVoxCount + GetShapeVoxelCount(allShapes[i])
	end

	local newPercentage = math.floor(currentVoxCount / totalVoxCount*1000)/10
	if percentage < 100 and not GetBool("level.demolish.fireworks") then
		if percentage < warnPercent then
			warnTime = GetTime()
			SetString("hud.notification","Áùè¼öé òõöòôòêñº, ýöòäº ñé óòåôéèìö¼ úùè-îòôö óéôéè ñãýãïòð úéíéôåéôîã")			
			warnPercent = percentage
		end
		if percentage < 100-gracePercent then
			SetString("hud.notification","Õùè-îòôö äºï óòåôéêèéñ")
			SetString("level.state","fail_busted")
		end
	end


	if newPercentage < percentage then
		outline = 2.0
		SetValue("outline", 0.0, "linear", 0.5)
		percentage = newPercentage
		SetFloat("level.demolish.percentage", percentage)

		if percentage < 100-gracePercent then
			SetBool("level.disablequicksave", true)
		end
		if percentage <= 10 then			
			done = true			
		end
	end
end

function update(dt)
	--Drive away
	if GetString("level.state") == "win" then
		if speed == 0 then
			PlaySound(sound)
			for i=1,#shapes do
				SetShapeEmissiveScale(shapes[i], 1.0)
			end
			--Close hatch on trucks
			if hatch ~= 0 then
				local t = GetShapeLocalTransform(hatch)
				t.rot = Quat()
				SetShapeLocalTransform(hatch, t)
			end
		end
		speed = speed + pAcceleration * dt
		if speed > pMaxSpeed then speed = pMaxSpeed end
		local vel = VecScale(dir, speed)
		transform.pos = VecAdd(transform.pos, VecScale(vel, dt))
		if pDynamic then
			SetBodyDynamic(body, true)
			SetBodyVelocity(body, vel)
		end
		SetBodyTransform(body, transform)
	end
end

function draw()
	-- Rest notification
	if not rested then
		local x, y, d = UiWorldToPixel(GetBodyTransform(body).pos)
		if d > 0 then
			local restInVanAlpha = math.min(math.max(1.0-(d-10)/5, 0.0), 1.0)
			UiPush()
				UiFont("bold.ttf", 24)
				UiTranslate(x, y - 50)
				UiAlign("center middle")
				local msg = "Óÿãöéï¼ñò óòèçòöòå¼öéõ¼, ã ëãöéð òöèòûñìöé å úùôçòñé"
				local w, h = UiGetTextSize(msg)
				UiColorFilter(1, 1, 1, restInVanAlpha)
				UiColor(1,1,1,0.5)
				UiImageBox("ui/common/box-solid-10.png", w+20, h+10, 6, 6)
				UiColor(0, 0, 0)
				UiText(msg)
			UiPop()
		end
	end

	if GetString("level.state") ~= "" then
		return
	end

	local dist = VecSub(GetPlayerTransform().pos, GetBodyTransform(center).pos)
	dist = VecLength(dist)

	if dist > 30 and dist < 70 then
		SetValue("screenUiY", 0.0, "linear", 0.3)
		SetValue("worldUiY", 1.0, "linear", 0.3)
	elseif dist <= 30 then
		SetValue("screenUiY", 1.0, "linear", 0.3)
		SetValue("worldUiY", 0.0, "linear", 0.3)
	end
	if dist > 70 then
		SetValue("screenUiY", 0.0, "linear", 0.3)
		SetValue("worldUiY", 0.0, "linear", 0.3)
	end

	if label ~= 0 and GetBool("level.demolish.fireworks") then
		local y = 70
		if GetBool("hud.hasnotification") then
			y = y + 50
		end
		UiTranslate(UiCenter()+10, y)
		UiPush()
			UiFont("bold.ttf", 22)
			UiTranslate(-230, 26)
			UiTextOutline(0,0,0,1)
			UiText("ÕÔÄ-ËÏÑÓ")
			UiTranslate(340, 0)
			UiText(percentage .. "%")
		UiPop()
		UiTranslate(-100, 10)
		progressBar(200, 20, math.max(math.min(percentage/100, 100), 0))
	end

	if fadeToBlackAlpha > 0 then
		UiPush()
			UiColor(0, 0, 0, fadeToBlackAlpha-fadeInAlpha)
			UiTranslate(UiCenter(), UiMiddle())
			UiAlign("center middle")
			UiRect(UiWidth(), UiHeight())
		UiPop()
	end
end