#include "script/common.lua"


local explosivebox = nil

function rnd(mi, ma)
	return math.random(1000)/1000*(ma-mi) + mi
end

function rndVec(t)
	return Vec(rnd(-t, t), rnd(-t, t), rnd(-t, t))
end

function init()

	explosivebox = FindShapes("explosivebox", true)
	explosionPos = Vec()
	deadCamDist = 1
	deadTime = 0
	deadExplosion = false
	deadExplosion2 = false
	deadExplosion3 = false
	
end

function tickExplosion(dt)
		deadTime = deadTime + dt

		if deadTime > 0.3 and not deadExplosion then
			Explosion(explosionPos, 4.0)
			SetString("level.state", "fail")
			deadExplosion = true
		end
		if deadTime > 0.6 and not deadExplosion2 then
			Explosion(VecAdd(explosionPos, Vec(-2, 0, 2)), 4.0)
			deadExplosion2 = true
		end
		if deadTime > 0.9 and not deadExplosion3 then
			Explosion(VecAdd(explosionPos, Vec(-4, 0, -2)), 4.0)
			deadExplosion3 = true
		end
		local target = explosionPos
		local dir = VecNormalize(Vec(1, 1, -1))
		local eye = VecAdd(target, VecScale(dir, deadCamDist))
		local t = Transform(eye, QuatLookAt(eye, target))
		SetCameraTransform(t, 90)
		SetTimeScale(0.2)
		
		ParticleTile(5)
		ParticleCollide(0)
		ParticleColor(1, 0.6, 0.4, 1, 0.3, 0.2)
		ParticleEmissive(6.0, 0.0, "easeout")
		ParticleAlpha(math.min(1.0, deadTime), 0)
		ParticleRadius(0.3, 5.0)
		for i=1, 5 do
		SpawnParticle(target, Vec(rnd(-5, 5), rnd(0, 2), rnd(-5,5)), rnd(0.5, 1.0)*(1.0+deadTime)*2.0)	
		end

		ParticleReset()
		ParticleType("plain")
		ParticleColor(0.8, 0.75, 0.7)
		ParticleAlpha(math.min(1.0, deadTime), 0)
		ParticleRadius(0.4, 3.0)
		for i=1, 5 do
			SpawnParticle(target, Vec(rnd(-8, 8), rnd(0, 2), rnd(-8,8)), rnd(0.5, 1.0)*(1.0+deadTime)*2.0)	
		end
		
		PointLight(VecAdd(target, Vec(0, 1, 0)), 1, 0.5, 0.2, 1000*math.min(1.0, deadTime))
end

function tick(dt)

	if dead then
		tickExplosion(dt)
	else
		checkShock()
	end
end

function update(dt)
	if not dead and GetFireCount() > 0 then
		for i=1, #explosivebox do			
			local min, max = GetShapeBounds(explosivebox[i])
			if QueryAabbFireCount(min, max) > 0 then
				dead = true
				return
			end
		end
	end

end

function checkShock()
	local hasBreakage = GetBool("game.break")
	if hasBreakage then
		local breakPoint = Vec(GetFloat("game.break.x"), GetFloat("game.break.y"), GetFloat("game.break.z"))
		for i = 1, #explosivebox do
			if VecLength(VecSub(breakPoint, GetShapeWorldTransform(explosivebox[i]).pos)) < 1 and not dead then
				explosionPos = breakPoint
				deadCamDist = 3
				deadTime = 0
				dead = true
			end
		end
	end
end

function handleCommand(cmd)
	if cmd == "quickload" then
	--from scene init
		explosivebox = FindShapes("explosivebox", true)
	end
end