include("shared.lua")

function ENT:UpdateModules()
	if self.ModuleSocket then
		for i = 1, #self.ModuleSocket do
			local ent = self.ModuleSocket[i]
			if IsValid(ent) then
				local aPoint = zrush.utility.MachineSockets[self.MachineID][i]
				local attach = self:GetAttachment(aPoint)
				if !attach then continue end
				ent:SetPos(attach.Pos)
				local ang = attach.Ang
				ang:RotateAroundAxis(attach.Ang:Right(), -90)
				ang:RotateAroundAxis(attach.Ang:Up(), -180)
				ent:SetAngles(ang)
				ent:DrawModel()
			else
				self.ModuleSocket = nil
				break
			end
		end
	end

	if !self.ModuleSocket then
		local count = math.Clamp(zrush.config.Machine[self.MachineID].Module_Sockets, 1, table.Count(zrush.utility.MachineSockets[self.MachineID]))
		self.ModuleSocket = self.ModuleSocket or {}

		for i = 1, count do
			local aPoint = zrush.utility.MachineSockets[self.MachineID][i]
			local attach = self:GetAttachment(aPoint)
			if !attach then continue end
			local socket = ClientsideModel("models/zerochain/props_oilrush/zor_module_socket.mdl")
			if !IsValid(socket) then return end
			socket:SetPos(attach.Pos)
			local ang = attach.Ang
			ang:RotateAroundAxis(attach.Ang:Right(), -90)
			ang:RotateAroundAxis(attach.Ang:Up(), -180)
			socket:SetAngles(ang)
			socket:SetNoDraw(true)
			socket:DrawModel()
			table.insert(self.ModuleSocket, socket)
		end
	end
end

function ENT:Draw()
	self:DrawModel()
	self:UpdateModules()
end

function ENT:Initialize()
	self:UpdatePitch()

	self.UpdateSound = false
end

function ENT:UpdatePitch()
	local basePitch = 100 / (zrush.config.Machine["Pump"].Speed / 4)
	self.SoundPitch = math.Clamp(basePitch + (140 * self:GetSpeedBoost()), 0, 140)
end

// This Updates some of the Sound Info
function ENT:UpdateSoundInfo()
	self:UpdatePitch()
	self.UpdateSound = true
end

local localPly
local updateDistance = GetConVar("mg_rush_cl_vfx_updatedistance")

function ENT:Think()
	localPly = localPly or LocalPlayer()

	if zrush.f.InDistance(localPly:EyePos(), self:GetPos(), updateDistance:GetFloat()) then
		local tb = self:GetTable()
		if !tb then return end
		local dt = tb.dt
		if !dt then return end

		// One time Effect Creation

		local cur_state = dt.State
		if tb.LastState ~= cur_state then
			tb.LastState = cur_state
		end

		// Playing looped sound
		zrush.f.LoopedSound(self, "zrush_sfx_jammed", dt.Jammed == true and cur_state == "JAMMED", 70)
		zrush.f.LoopedSound(self, "zrush_sfx_pump", dt.Jammed == false and cur_state == "PUMPING", tb.SoundPitch)
	end

	self:SetNextClientThink(CurTime())
	return true
end

function ENT:OnRemove()
	if self.ModuleSocket then
		for i = 1, #self.ModuleSocket do
			local ent = self.ModuleSocket[i]
			SafeRemoveEntity(self.ModuleSocket[i])
		end
	end

	self:StopSound("zrush_sfx_pump")
	self:StopSound("zrush_sfx_jammed")
	self:StopParticles()
end