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()
	
	if ( !self:GetSWEP():CheckLimit( "lamps" ) ) then return false end
	
	local pos, ang = trace.HitPos + trace.HitNormal * 10, trace.HitNormal:Angle() - Angle( 90, 0, 0 )

	local r 	= tonumber( self:GetClientInfo( "r" ) )
	local g 	= tonumber( self:GetClientInfo( "g" ) )
	local b 	= tonumber( self:GetClientInfo( "b" ) )
	
	lamp = MakeLamp( ply, pos, ang, r, g, b )
	
	if (!attach) then 
	
		undo.Create("Lamp")
		undo.AddEntity( lamp )
		undo.SetPlayer( self:GetOwner() )
		undo.Finish()
		
		return true
		
	end

	local length 	= tonumber( self:GetClientInfo( "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()

	ply:AddCleanup( "lamps", lamp )
	
	return true

end

function TOOL:RightClick( trace )

	return self:LeftClick( trace, false )

end

function MakeLamp( pl, Pos, Ang, r, g, b, Vel, aVel, frozen )

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

	local lamp = ents.Create( "gmod_lamp" )
	if (!lamp:IsValid()) then return end
		lamp:SetPos( Pos )
		lamp:SetAngles( Ang )
		lamp:GetTable():SetLightColor( r, g, b )
	lamp:Spawn()
	
	lamp:GetTable():SetPlayer( pl )

	if (lamp:GetPhysicsObject():IsValid()) then
		Phys = lamp:GetPhysicsObject()
		if Vel then Phys:SetVelocity(Vel) end
		if Vel then Phys:AddAngleVelocity(aVel) end
		Phys:EnableMotion(frozen != true)
	end
	
	pl:AddCount( "lamps", lamp )
	
	return lamp
end

duplicator.RegisterEntityClass( "gmod_lamp", MakeLamp, "Pos", "Ang", "lightr", "lightg", "lightb", "Vel", "aVel", "frozen" )
