if SERVER then
	AddCSLuaFile()
end

DEFINE_BASECLASS("wdj_audiosource")

ENT.Base = "wdj_audiosource"

ENT.PrintName = "Radio"
ENT.Category = "DJ"

ENT.Spawnable = true

ENT.RenderGroup = RENDERGROUP_BOTH
ENT.Model = Model("models/props_lab/citizenradio.mdl")

function ENT:Initialize()
	self.BaseClass.Initialize(self)
	if SERVER then
		self:SetModel(self.Model)
		self:PhysicsInit(SOLID_VPHYSICS)
		self:SetMoveType(MOVETYPE_VPHYSICS)
		self:SetSolid(SOLID_VPHYSICS)
		self:SetUseType(SIMPLE_USE)
		self:CPPISetOwner(self:Getowning_ent())
	end
end

if CLIENT then
	local tdui = wdj.tdui

	local icon_muted = Material("icon16/sound_mute.png")
	local cvar_vol = GetConVar("wdj_volume")

	local MAXVISDISTANCE_SQ = math.pow(256, 2)
	local local_ply, distsq, maxdist
	function ENT:Draw()
		self:DrawModel()
	end

	function ENT:DrawTranslucent()
		local_ply = local_ply or LocalPlayer()
		distsq = self:GetPos():DistToSqr(local_ply:EyePos())
		maxdist = MAXVISDISTANCE_SQ
		if distsq > maxdist then return end
		local size_mul = 5
		self.ui = self.ui or tdui.Create()
		local master = wdj.GetMaster(self:GetChannel())
		local name
		if IsValid(master) then
			name = master:GetChannelNameFormatted()
		else
			name = string.format("Channel #%d", self:GetChannel())
		end
		self.ui:Rect(-50 * size_mul, 11 * size_mul, 150 * size_mul, 30 * size_mul, Color(0, 0, 0, 235), color_white)
		self.ui:Text(name, "WDJ_ControllerFont2", 25 * size_mul, 12 * size_mul)
		if (cvar_vol:GetFloat() == 0) then
			self.ui:Mat(icon_muted, 84 * size_mul, 20 * size_mul, 12 * size_mul, 12 * size_mul)
		end
		self.ui:Render(self:LocalToWorld(Vector(8.5, 0, 16.5)), self:LocalToWorldAngles(Angle(0, 180, 0)), 0.022)
	end

	local frame
	local function OpenRadioConfig(ent)
		if IsValid(frame) then return end
		frame = vgui.Create("DFrame")
		frame:SetTitle("Radioeinstellungen")
		frame:SetSkin("WyoziCK")
		frame:SetSize(300, 105)
		frame:Center()
		local ply = LocalPlayer()
		frame.Think = function(slf)
			if !IsValid(ent) or ply:EyePos():DistToSqr(ent:GetPos()) > 22500 then
				frame:Close()
			end
		end
		local vol = vgui.Create("DNumSlider", frame)
		vol:SetPos(15, 30)
		vol:SetSize(290, 30)
		vol:SetText("Volumen")
		vol:SetDark(true)
		vol:SetMin(0)
		vol:SetMax(1)
		vol:SetConVar("wdj_volume")
		local chan = vgui.Create("DLabel", frame)
		chan:SetPos(15, 75)
		chan:SetSize(50, 10)
		chan:SetText("Channel")
		chan:SetDark(true)
		local sel = vgui.Create("WDJChannelSelector", frame)
		sel:SetPos(135, 67.5)
		sel:SetSize(150, 25)
		if ent.GetChannel then
			sel:SetChannel(ent:GetChannel())
		end
		sel.OnChange = function(newchan)
			if !IsValid(ent) then return end
			net.Start("WDJ_Radio_ChannelChange")
				net.WriteEntity(ent)
				net.WriteUInt(newchan, 8)
			net.SendToServer()
		end
		frame:MakePopup()
		frame:ParentToHUD()
	end

	concommand.Add("wdj_openradioconfig", function(ply, cmd, args)
		if !tonumber(args[1]) then return end
		OpenRadioConfig(Entity(tonumber(args[1])))
	end)

	local PANEL = {}
	function PANEL:Init()
		self.DecrButton = vgui.Create("DButton", self)
		self.DecrButton:SetText("<")
		self.DecrButton.DoClick = function() self:AdvanceChannel(-1) end
		self.DecrButton:Dock(LEFT)
		self.ChannelText = vgui.Create("DTextEntry", self)
		self.ChannelText:SetDisabled(true)
		self.ChannelText:Dock(FILL)
		self.IncrButton = vgui.Create("DButton", self)
		self.IncrButton:SetText(">")
		self.IncrButton.DoClick = function() self:AdvanceChannel(1) end
		self.IncrButton:Dock(RIGHT)
	end

	function PANEL:PerformLayout()
		local w, h = self:GetSize()
		self.DecrButton:SetPos(0, 0)
		self.DecrButton:SetSize(32, h)
		self.IncrButton:SetPos(w - 32, 0)
		self.IncrButton:SetSize(32, h)
		self.ChannelText:SetPos(32, 0)
		self.ChannelText:SetSize(w - 64, h)
	end

	function PANEL:SetChannel(chan, change)
		self.Channel = chan
		local m = wdj.GetMaster(chan)
		self.ChannelText:SetText(IsValid(m) and m:GetChannelNameFormatted() or "Channel #0")
		if change then
			self.OnChange(chan)
		end
	end

	function PANEL:GetChannel()
		return self.Channel or 0
	end

	function PANEL:AdvanceChannel(delta)
		local delta_sig = wdj.signum(delta)
		for i=0, wdj.MAX_CHANNELS do
			local newch = (self:GetChannel() + delta + i * delta_sig) % wdj.MAX_CHANNELS
			local m = wdj.GetMaster(newch)
			if IsValid(m) then
				self:SetChannel(newch, true)
				break
			end
		end
	end
	derma.DefineControl("WDJChannelSelector", "A channel selector", PANEL, "Panel")
end

if SERVER then
	function ENT:Use(ply)
		ply:ConCommand("wdj_openradioconfig "..self:EntIndex())
	end

	util.AddNetworkString("WDJ_Radio_ChannelChange")
	net.Receive("WDJ_Radio_ChannelChange", function(len, cl)
		local ent = net.ReadEntity()
		if !IsValid(ent) or ent:GetClass() != "wdj_radio" then return end
		local delta = net.ReadUInt(8)
		ent:SetChannel(delta % wdj.MAX_CHANNELS)
	end)
end