
TOOL.Category		= "Construction"
TOOL.Name			= "#Lamps"
TOOL.Command		= nil
TOOL.ConfigName		= nil

TOOL.ClientConVar[ "ropelength" ] = "64"
TOOL.ClientConVar[ "ropematerial" ] = "cable/rope"
TOOL.ClientConVar[ "r" ] = "255"
TOOL.ClientConVar[ "g" ] = "255"
TOOL.ClientConVar[ "b" ] = "255"

cleanup.Register( "lamps" )

function TOOL:LeftClick( trace, attach )

	if trace.Entity && trace.Entity:IsPlayer() then return false end
	if (CLIENT) then return true end
	if (attach == nil) then attach = true end
	
	// If there's no physics object then we can't constraint it!
	if ( SERVER && attach && !util.IsValidPhysicsObject( trace.Entity, trace.PhysicsBone ) ) then return false end
	
	local ply = self:GetOwner()
	
	local pos, ang = trace.HitPos + trace.HitNormal * 10, trace.HitNormal:Angle() - Angle( 90, 0, 0 )

	local r 	= math.Clamp( self:GetClientNumber( "r" ), 0, 255 )
	local g 	= math.Clamp( self:GetClientNumber( "g" ), 0, 255 )
	local b 	= math.Clamp( self:GetClientNumber( "b" ), 0, 255 )
	
	if	trace.Entity:IsValid() && 
		trace.Entity:GetClass() == "gmod_lamp" &&
		trace.Entity:GetTable():GetPlayer() == ply
	then
		trace.Entity:GetTable():SetLightColor( r, g, b )
		trace.Entity:GetTable().r = r
		trace.Entity:GetTable().g = g
		trace.Entity:GetTable().b = b
		return true
	end
	
	if ( !self:GetSWEP():CheckLimit( "lamps" ) ) then return false end
	lamp = MakeLamp( ply, r, g, b, { Pos = pos, Angle = ang } )
	
	if (!attach) then 
	
		undo.Create("Lamp")
			undo.AddEntity( lamp )
			undo.SetPlayer( self:GetOwner() )
		undo.Finish()
		
		return true
		
	end

	local length 	= self:GetClientNumber( "ropelength" )
	local material 	= self:GetClientInfo( "ropematerial" )
	
	local LPos1 = Vector( 0, 0, 5 )
	local LPos2 = trace.Entity:WorldToLocal( trace.HitPos )
	
	if (trace.Entity:IsValid()) then
		
		local phys = trace.Entity:GetPhysicsObjectNum( trace.PhysicsBone )
		if (phys:IsValid()) then
			LPos2 = phys:WorldToLocal( trace.HitPos )
		end
	
	end
	
	local constraint, rope = constraint.Rope( lamp, trace.Entity, 
											  0, trace.PhysicsBone, 
											  LPos1, LPos2, 
											  0, length,
											  0, 
											  1.5, 
											  material, 
											  nil )
	
	undo.Create("Lamp")
		undo.AddEntity( lamp )
		undo.AddEntity( rope )
		undo.AddEntity( constraint )
		undo.SetPlayer( ply )
	undo.Finish()

	return true

end

function TOOL:RightClick( trace )

	return self:LeftClick( trace, false )

end

function MakeLamp( pl, r, g, b, Data )

	if ( !pl:CheckLimit( "lamps" ) ) then return false end

	local lamp = ents.Create( "gmod_lamp" )
	
		if (!lamp:IsValid()) then return end
	
		duplicator.DoGeneric( lamp, Data )
		lamp:SetLightColor( r, g, b )
		
	lamp:Spawn()
	
	duplicator.DoGenericPhysics( lamp, pl, Data )
	
	lamp:SetPlayer( pl )

	pl:AddCount( "lamps", lamp )
	pl:AddCleanup( "lamps", lamp )
	
	return lamp
end

duplicator.RegisterEntityClass( "gmod_lamp", MakeLamp, "lightr", "lightg", "lightb", "Data" )
