#include "script/toolanimation.lua"
 
 function init()
	RegisterTool("tnt", "loc@TOOL_NAME_TNT", "MOD/prefabs/tools/tnt_flask.xml", 4)
	--SetBool("game.tool.TNT.enabled", true)
	--SetInt("game.tool.tnt.ammo", 1)
	toolAnimator = ToolAnimator()
end

function tick(dt)
	if GetString("game.player.tool") == "tnt" then
		if GetInt("game.tool.tnt.ammo") > 0 then
			toolAnimator.offsetTransform = Transform(Vec(0.3, -0.37, -0.55))

			local playerT = GetPlayerCameraTransform()

			if InputPressed("usetool") and GetBool("game.player.canusetool") then
				local depth = 4.5
				if GetBool("game.thirdperson") then depth = 6 end
				local hit, dist, normal, shape = QueryRaycast(playerT.pos, QuatRotateVec(playerT.rot, Vec(0, 0, -1)), depth)
				if  hit then
					if HasTag(shape, "horse") then return end
					local hitPos = TransformToParentPoint(playerT, Vec(0, 0, -dist))
					if normal[2] > 0.9 then
						local rotation = QuatLookAt(Vec(hitPos[1], 0, hitPos[3]), Vec(playerT.pos[1], 0, playerT.pos[3]))
						local spawnTransform = Transform(hitPos, rotation)
						local entities = Spawn("MOD/prefabs/tools/TNT.xml", spawnTransform, true)
					else
						local xAxis = Vec(1.0, 0, 0)
						normal = VecScale(normal, -1.0)
						local rotateAxis = VecCross(xAxis, normal)
						rotateAxis = VecNormalize(rotateAxis)
						local angle = (180.0 / math.pi) * math.acos(VecDot(xAxis, normal) / (VecLength(xAxis) * VecLength(normal)))
						local spawnTransform = Transform(hitPos, QuatAxisAngle(rotateAxis, angle))
						local entity = Spawn("MOD/prefabs/tools/TNT_rope.xml", spawnTransform, false, false)

						local newbody = GetShapeBody(shape)
						local newtransform = Transform()
						if newbody~= 1 then
							newtransform = TransformToLocalTransform(GetBodyTransform(newbody), GetShapeWorldTransform(entity[3]))
						else
							newtransform = TransformToParentTransform( GetBodyTransform(newbody), GetShapeWorldTransform(entity[3]))
						end

						SetShapeBody(entity[3], newbody, newtransform)
					end
					SetInt("game.tool.tnt.ammo", GetInt("game.tool.tnt.ammo")-1)
					return
				end
			end
		else
			toolAnimator.offsetTransform = Transform(Vec(0, -100, 0))
		end
		if getEyeHeight() < 0.9 then
			toolAnimator.armPitchScale = 0.0
			toolAnimator.toolPitchScale = 0.3
		else
			toolAnimator.armPitchScale = 0.4
			toolAnimator.toolPitchScale = 0.3
		end
		tickToolAnimator(toolAnimator, dt)
	end
end