#include "../common/utils.lua"

function init()
	dynamiteBundle = FindBody("dynamite_bundle")
	if HasTag(dynamiteBundle, "rope") then
		ropeTransform = Transform(Vec(0.02, 0.22, 0.24))
	else
		ropeTransform = Transform(Vec(0.02, 0.12, 0.24))
	end
	dynamiteshapes = FindShapes()
	sound = LoadLoop("tools/blowtorch-hit-loop.ogg", 5.0)
end

local lifeTimer = 0.0
local explosionTimer = 4

function tick(dt)
	if not IsHandleValid(dynamiteBundle) then
		return
	end

	local dynamiteShapeTransform = GetShapeWorldTransform(dynamiteshapes[1])
	lifeTimer = lifeTimer + dt
	if lifeTimer >= explosionTimer then
		Explosion(dynamiteShapeTransform.pos, GetFloat("game.tool.dynamite_bundle.damage"))
		for i = 1, #dynamiteshapes do Delete(dynamiteshapes[i]) end
		Delete(dynamiteBundle)
	end

	ParticleReset()
	ParticleTile(6)
	ParticleColor(1, 0.6, 0.1, 1, 0.2, 0.2)
	ParticleRadius(0.01)
	ParticleCollide(0, 1)
	ParticleGravity(0.5, "fadeout")
	ParticleStretch(0.7)
	ParticleAlpha(0.8, 0.2)
	ParticleEmissive(5, 0)

	local sparksPos = TransformToParentTransform(dynamiteShapeTransform, ropeTransform)
	for i = 1, 6 do
		local sparksDir = QuatRotateVec(sparksPos.rot, Vec(rnd(-2, 2), rnd(-3, 3), rnd(-2, 2)))
		SpawnParticle(sparksPos.pos, sparksDir, rnd(0.2, 0.4))
	end

	SetLightIntensity(light, rnd(0.3, 0.8))
	PlayLoop(sound, sparksPos.pos)
end