include("shared.lua")

net.Receive("MG_CarDealer_TuneData_S2C", function(len,ply)
	local T = net.ReadTable()
	local ent = T.ent
	local tundedata = T.tunedata
	if IsValid(ent) and ent.SetTuneData then
		ent:SetTuneData(tundedata)
	end
end)

local TuneSysEntities = {}
function ENT:Initialize()
	self:SetRenderBounds(Vector(-300, -300, -300), Vector(300, 300, 300))
	TuneSysEntities[self:EntIndex()] = self
end

function ENT:GetEmitter()
	self.Emitter = self.Emitter or ParticleEmitter(self:GetPos())
	if self.Emitter then
		return self.Emitter
	end
end

function ENT:Draw()
	if !self.TuneData then
		self.TuneData = {}
		net.Start("MG_CarDealer_RequestTuneData_C2S")
			net.WriteEntity(self)
		net.SendToServer()
	end
end

function ENT:Think()
	local tunedata = self.TuneData
	if tunedata then
		for _, data in pairs(tunedata.Elements or {}) do
			local element = MG_CarDealer_Tuners[data.Type]
			if element then
				element:CL_Think(self, data.Vars)
			end
		end
	end
end

local dist = MG_CarDealerConfig.TuneRenderDist * MG_CarDealerConfig.TuneRenderDist
local local_ply
local function DrawTuners()
	local_ply = local_ply or LocalPlayer()
	local pos
	for k, v in pairs(TuneSysEntities) do
		if IsValid(v) then
			pos = pos or local_ply:EyePos()
			if !v:IsDormant() and v:GetPos():DistToSqr(pos) < dist then
				v:DrawElements(v.TuneData or {})
			end
		else
			TuneSysEntities[k] = nil
		end
	end
end

hook.Add("PostDrawTranslucentRenderables", "MG_CarDealer_DrawTuners", DrawTuners)

function ENT:SetTuneData(data)
	self.TuneData = data
end

function ENT:DrawElements(tunedata)
	cam.Start3D(EyePos(), EyeAngles())
		for _, data in pairs(tunedata.Elements or {}) do
			local element = MG_CarDealer_Tuners[data.Type]
			if element then
				element:Render(self, data.Vars)
			end
		end
	cam.End3D()
end