include("shared.lua")

local localPly
local updateDistance = GetConVar("mg_rush_cl_vfx_updatedistance")

function ENT:Draw()
	self:DrawModel()
	localPly = localPly or LocalPlayer()

	if !zrush.f.InDistance(localPly:EyePos(), self:GetPos(), updateDistance:GetFloat()) or self:GetNoDraw() then
		self:Remove_ClientPipes()
		self.LastPipeCount = 0
		self.ClientPipesRebuild = false
	else
		if ((self.LastPipeCount or 0) ~= self:GetPipeCount()) or self.ClientPipesRebuild == false then
			self:Rebuild_ClientPipes()
			self.LastPipeCount = self:GetPipeCount()
		else
			self:Parent_ClientPipes()
		end
	end
end

function ENT:Initialize()
	self.ClientPipesRebuild = false
	zrush.f.EntList_Add(self)
end

function ENT:Parent_ClientPipes()
	local tb = self:GetTable()
	if !tb then return end

	if tb.Pipes then
		for i = 1, #tb.Pipes do
			local pipe = tb.Pipes[i]

			if IsValid(pipe) then
				local attach = self:GetAttachment(i)

				if !IsValid(pipe:GetParent()) and attach then
					pipe:SetPos(attach.Pos)
					local ang = attach.Ang
					ang:RotateAroundAxis(self:GetForward(), 90)
					ang:RotateAroundAxis(self:GetRight(), 90)
					pipe:SetAngles(ang)
				end
				
				pipe:DrawModel()
			end
		end
	end
end

function ENT:Remove_ClientPipes()
	local tb = self:GetTable()
	if !tb then return end

	if tb.Pipes then
		for i = 1, #tb.Pipes do
			local pipe = tb.Pipes[i]

			SafeRemoveEntity(pipe)
		end
	end

	tb.Pipes = {}
end

// This spawns the visual pipes in the holder
function ENT:Rebuild_ClientPipes()
	local tb = self:GetTable()
	if !tb then return end
	local dt = tb.dt
	if !dt then return end

	self:Remove_ClientPipes()
	tb.Pipes = {}

	for i = 1, dt.PipeCount do
		local attach = self:GetAttachment(i)

		if attach then
			local pipe = ClientsideModel("models/zerochain/props_oilrush/zor_drillpipe.mdl")

			if IsValid(pipe) then
				pipe:SetPos(attach.Pos)
				local ang = attach.Ang
				ang:RotateAroundAxis(self:GetForward(), 90)
				ang:RotateAroundAxis(self:GetRight(), 90)
				pipe:SetAngles(ang)

				pipe:SetParent(self)

				pipe:SetNoDraw(true)

				pipe:DrawModel()

				table.insert(tb.Pipes, pipe)
			end
		end
	end

	tb.ClientPipesRebuild = true
end

function ENT:OnRemove()
	self:Remove_ClientPipes()
end
