
TOOL.ClientConVar[ "group" ] = 1	// Current group
TOOL.ClientConVar[ "health" ] = 0	// Health (shoot it to blow it up)
TOOL.ClientConVar[ "damage" ] = 200	// Damage to inflict
TOOL.ClientConVar[ "delay" ] = 0	// Delay before explosions start
TOOL.ClientConVar[ "delay_add" ] = 0.1	// Delay beween each dynamite
TOOL.ClientConVar[ "remove" ] = 0	// Remove on explode

TOOL.Model = "models/dav0r/tnt/tnt.mdl"

cleanup.Register( "dynamite" )

function TOOL:LeftClick( trace )

	if (!trace.HitPos) then return false end
	if (trace.Entity:IsPlayer()) then return false end
	if ( CLIENT ) then return true end
	
	local ply = self:GetOwner()
	
	if ( !self:GetSWEP():CheckLimit( "dynamite" ) ) then return false end

	// Get client's CVars
	local _group		= tonumber( self:GetClientInfo( "group" ) )
	local _remove 		= tonumber( self:GetClientInfo( "remove" ) )
	local _health 		= tonumber( self:GetClientInfo( "health" ) )
	local _damage 		= mathx.Max( tonumber( self:GetClientInfo( "damage" ) ), 0 )
			
	local dynamite = MakeDynamite( ply, trace.HitPos, Angle( 90, 0, 0 ), _group, _remove, _health, _damage )
	
	local min = dynamite:OBBMins()
	dynamite:SetPos( trace.HitPos - trace.HitNormal * min.z )

	undo.Create("Dynamite")
	undo.AddEntity( dynamite )
	undo.SetPlayer( ply )
	undo.Finish()
	
	ply:AddCount( "dynamite", dynamite )
	ply:AddCleanup( "dynamite", dynamite )
	
	return true
	
end

function TOOL:RightClick( trace )

	return self:LeftClick( trace )
	
end

if SERVER then
	function MakeDynamite(pl, Pos, Ang, key, remove, health, damage, Vel, aVel, frozen )

		local dynamite = ents.Create( "gmod_dynamite" )
			dynamite:SetKeyValue( "health", health )
			dynamite:SetKeyValue( "damage", damage )
			if ( remove ~= 0 ) then dynamite:SetKeyValue( "remove", 1 ) end
			dynamite:SetPos( Pos )
		dynamite:Spawn()
		dynamite:SetAngles( Ang )

		if dynamite:GetPhysicsObject():IsValid() then
			Phys = dynamite:GetPhysicsObject()
			if Vel then Phys:SetVelocity(Vel) end
			if Vel then Phys:AddAngleVelocity(aVel) end
			Phys:EnableMotion(frozen != true)
		end
		dynamite:Activate()
		
		// Create the tables if they don't exist
		if ( !pl:GetTable().Dynamite ) then pl:GetTable().Dynamite = {} end
		if ( !pl:GetTable().Dynamite[key] ) then
			pl:GetTable().Dynamite[key] = {}
			
			// Only register the numpad key once, otherwise we end up with explosions happening several times
			numpad.OnDown( pl, key, "DynamiteBlow", nil, {key} )
			
		end
		
		// Put the dynamite in a table for later reference
		table.insert( pl:GetTable().Dynamite[key], dynamite )
		
		local dtable = {
			key	  = key,
			remove	  = remove,
			health	  = health,
			damage    = damage,
			}

		tablex.Merge(dynamite:GetTable(), dtable )

		return dynamite
	end
	duplicator.RegisterEntityClass( "gmod_dynamite", MakeDynamite, "Pos", "Ang", "key", "remove", "health", "damage", "Vel", "aVel", "frozen" )
	
	function CC_Dynamite_Explode( pl, command, arguments )
	
		arguments = arguments or {}
	
		local _group =		tonumber(arguments[1] or pl:GetInfo( "dynamite_group" ))
		local _delay =		tonumber(arguments[2] or pl:GetInfo( "dynamite_delay" ))
		local _delay_add =	tonumber(arguments[3] or pl:GetInfo( "dynamite_delay_add" ))
		local _i = 0
		
		if ( !pl:GetTable().Dynamite ) then return end
		if ( !pl:GetTable().Dynamite[_group] ) then return end
		
		for key, value in pairs( pl:GetTable().Dynamite[_group] ) do
			if ( value:IsValid() ) then
				value:GetTable():Explode( _delay + (_delay_add * _i) )
				_i = _i + 1
			else
				table.remove( pl:GetTable().Dynamite[_group], key )
			end
		end
	end
	
	concommand.Add( "dynamite_explode", CC_Dynamite_Explode )
	numpad.Register( "DynamiteBlow", CC_Dynamite_Explode )
	
end

function TOOL:UpdateGhostDynamite( ent, player )

	if ( !ent ) then return end
	if ( !ent:IsValid() ) then return end

	local tr 	= utilx.GetPlayerTrace( player, player:GetCursorAimVector() )
	local trace 	= util.TraceLine( tr )
	
	if (!trace.Hit || trace.Entity:IsPlayer() ) then
		ent:SetNoDraw( true )
		return
	end
	
	local Ang = Angle( 90, 0, 0 )
	ent:SetAngles( Ang )	

	local min = ent:OBBMins()
	ent:SetPos( trace.HitPos - trace.HitNormal * min.z )
	
	ent:SetNoDraw( false )

end

function TOOL:Think()

	if (!self.GhostEntity || !self.GhostEntity:IsValid() || self.GhostEntity:GetModel() != self.Model ) then
		self:MakeGhostEntity( self.Model, Vector(0,0,0), Angle(0,0,0) )
	end
	
	self:UpdateGhostDynamite( self.GhostEntity, self:GetOwner() )
	
end