include("shared.lua")

ENT.Vol3dFadeMax = 256

surface.CreateFont("WDJ_ControllerFont1", {font = "Roboto", size = 80})
surface.CreateFont("WDJ_ControllerFont2", {font = "Roboto", size = 125})
surface.CreateFont("WDJ_ControllerFont3", {font = "Roboto", size = 65})

local titleCache = {}
local function GetUrlTitle(url)
	local cached = titleCache[url]
	if cached == true then return end
	if cached then return cached end
	titleCache[url] = true
	if wdj.ytapi.isPlaylistScheme(url) then
		local id, trid = wdj.ytapi.urlToPlsVideoId(url)
		wdj.ytapi.queryPlaylistMeta(id, function(err, data)
			if err then print("[DJ] An error occured: ", data) return end
			titleCache[url] = "[YT-Playlist] "..data.title.."@"..trid
		end)
	else
		wdj.medialib.load("media").guessService(url):query(url, function(err, data)
			if err then MsgN(err) return end
			titleCache[url] = data.title
		end)
	end
end

local cfg = {
	{
		text = "Stimme übertr.",
		key = "broadcastVoice",
		value = function(ent)
			return ent:GetBroadcastVoice()
		end
	},
	{
		text = "Lokaler Ton",
		key = "playSound",
		value = function(ent)
			return ent:GetPlaySound()
		end
	},
}

local tdui = wdj.tdui

local clr_yes = Color(135, 211, 124)
local clr_no = Color(210, 77, 87)

local icon_note = Material("icon16/music.png")
local clr_darker = Color(0, 0, 0, 250)

local function darker(clr)
	local h, s, v = ColorToHSV(clr)
	return HSVToColor(h, s + 0.2, v)
end

local MAXVISDISTANCE_SQ = math.pow(1024, 2)
local local_ply, eye_pos, distsq, maxdist
function ENT:Draw()
	self:DrawModel()
	local backside = self.Backside
	local isvalid = IsValid(backside)
	if !isvalid then
		self.Backside = ClientsideModel("models/props/de_nuke/nuclearcontrolbox.mdl")
		backside = self.Backside
		if IsValid(backside) then
			local pos, ang = LocalToWorld(Vector(0, -0.9, 0.05), Angle(0, 180, 0), self:GetPos(), self:GetAngles())
			backside:SetPos(pos)
			backside:SetAngles(ang)
			backside:SetParent(self)
			backside:SetModelScale(0.99, 0)
			backside:SetNoDraw(true)
			backside:DrawModel()
		end
	else
		if !IsValid(backside:GetParent()) then
			local pos, ang = LocalToWorld(Vector(0, -0.9, 0.05), Angle(0, 180, 0), self:GetPos(), self:GetAngles())
			backside:SetPos(pos)
			backside:SetAngles(ang)
			backside:SetParent(self)
			backside:DrawModel()
		else
			backside:DrawModel()
		end
	end
end

function ENT:DrawTranslucent()
	local_ply = local_ply or LocalPlayer()
	eye_pos = local_ply:EyePos()
	distsq = self:GetPos():DistToSqr(eye_pos)
	maxdist = MAXVISDISTANCE_SQ
	if distsq > maxdist then return end
	local norm = self:GetAngles():Forward()
	local epdiff = (eye_pos - self:GetPos())
	epdiff:Normalize()
	if norm:Dot(epdiff) < 0 then return end
	local size_mul = 5
	local uiy = 40
	local tb = self:GetTable()
	tb.ui = tb.ui or tdui.Create()
	tb.ui:Rect(-100 * size_mul, 0, 200 * size_mul, 220 * size_mul, clr_darker, tdui.COLOR_WHITE)
	tb.ui:EnableRectStencil(-99 * size_mul, 1 * size_mul, 198 * size_mul, 35 * size_mul)
	for i=1, 15 do
		local x = -120 + (i * 16 + CurTime() * 4) % 240
		tb.ui:Mat(icon_note, x * size_mul, 2 * size_mul, 16 * size_mul, 16 * size_mul)
	end
	for i=1, 15 do
		local x = -120 + (i * 16 - CurTime() * 4) % 240
		tb.ui:Mat(icon_note, x * size_mul, 18 * size_mul, 16 * size_mul, 16 * size_mul)
	end
	tb.ui:Rect(-100 * size_mul, 0, 200 * size_mul, 35 * size_mul, clr_darker)
	tb.ui:DisableStencil()
	tb.ui:Text("Radiokonsole", "WDJ_ControllerFont2", 0 * size_mul, 5 * size_mul, Color(149, 165, 166))
	tb.ui:Line(-100 * size_mul, 35 * size_mul, 100 * size_mul, 35 * size_mul)
	local name = self:GetChannelNameFormatted()
	tb.ui:Text(name, "WDJ_ControllerFont1", 0 * size_mul, 45 * size_mul)
	if tb.ui:Button("-1", "WDJ_ControllerFont1", -93 * size_mul, 43 * size_mul, 30 * size_mul, 20 * size_mul) then
		net.Start("WDJ_Controller_ChannelChange")
			net.WriteEntity(self)
			net.WriteInt(input.IsShiftDown() and -10 or -1, 8)
		net.SendToServer()
	end
	if tb.ui:Button("+1", "WDJ_ControllerFont1", 63 * size_mul, 43 * size_mul, 30 * size_mul, 20 * size_mul) then
		net.Start("WDJ_Controller_ChannelChange")
			net.WriteEntity(self)
			net.WriteInt(input.IsShiftDown() and 10 or 1, 8)
		net.SendToServer()
	end
	tb.ui:Line(-100 * size_mul, 70 * size_mul, 100 * size_mul, 70 * size_mul)
	for k,set in ipairs(cfg) do
		local clr = set.value(self) and clr_yes or clr_no
		if tb.ui:Button(set.text, "WDJ_ControllerFont3", (-95 + (k - 1) * 95) * size_mul, 75 * size_mul, 90 * size_mul, 15 * size_mul, clr, darker(clr)) then
			if distsq > 90000 then return end
			net.Start("WDJ_Controller_Configure")
				net.WriteEntity(self)
				net.WriteString(set.key)
			net.SendToServer()
		end
	end
	tb.ui:Line(-100 * size_mul, 95 * size_mul, 100 * size_mul, 95 * size_mul)
	tb.ui:Text("Jetzt:", "WDJ_ControllerFont3", 0 * size_mul, 100 * size_mul)
	tb.ui:EnableRectStencil(-100 * size_mul, 115 * size_mul, 200 * size_mul, 15 * size_mul)
	local t = self:GetCurMedia()
	if t == "--loading" then
		t = "Ladevorgang läuft..."
	elseif t != "" then
		t = GetUrlTitle(t) or t
	end
	tb.ui:Text(string.Left(t, 40), "WDJ_ControllerFont3", 0 * size_mul, 115 * size_mul)
	tb.ui:DisableStencil()
	if tb.ui:Button("Absp.", "WDJ_ControllerFont3", -93 * size_mul, 100 * size_mul, 30 * size_mul, 15 * size_mul) then
		if distsq > 90000 then return end
		if (self:WDJ_IsAllowed(local_ply) == true) then
			wdj.OpenVideoRequester("", function(url)
				net.Start("WDJ_Controller_SetNext")
					net.WriteEntity(self)
					net.WriteString(url)
				net.SendToServer()
			end)
		end
	end
	tb.ui:Line(-100 * size_mul, 135 * size_mul, 100 * size_mul, 135 * size_mul, Color(100, 100, 100))
	if tb.ui:Button("Überspr.", "WDJ_ControllerFont3", -93 * size_mul, 140 * size_mul, 50 * size_mul, 15 * size_mul) then
		if distsq > 90000 then return end
		net.Start("WDJ_Controller_Skip")
			net.WriteEntity(self)
		net.SendToServer()
	end
	if tb.ui:Button("Stopp.", "WDJ_ControllerFont3", -38 * size_mul, 140 * size_mul, 50 * size_mul, 15 * size_mul) then
		if distsq > 90000 then return end
		net.Start("WDJ_Controller_Stop")
			net.WriteEntity(self)
		net.SendToServer()
	end
	if tb.ui:Button("Umbenen.", "WDJ_ControllerFont3", 30 * size_mul, 140 * size_mul, 60 * size_mul, 15 * size_mul) then
		if distsq > 90000 then return end
		if (self:WDJ_IsAllowed(local_ply) == true) then
			Derma_StringRequest(
				string.format("Radiochannel \"%s\" umbenennen", name),
				"Hier kann der Name des derzeitigen Radiochannels bearbeitet werden.",
				"",
				function(text)
					net.Start("WDJ_Controller_Rename")
						net.WriteEntity(self)
						net.WriteString(text)
					net.SendToServer()
				end,
				function(text)
				end, "Akzeptieren", "Abbrechen"
			)
		end
	end
	tb.ui:Line(-100 * size_mul, 160 * size_mul, 100 * size_mul, 160 * size_mul)
	tb.ui:Text(string.format("Derzeitige Zuhörer: %d", self:GetNW2Int("listenerCount", 0)), "WDJ_ControllerFont3", 0 * size_mul, 165 * size_mul)
	tb.ui:Text(string.format("Radioanzahl: %d", self:GetNW2Int("radioCount", 0)), "WDJ_ControllerFont3", 0 * size_mul, 180 * size_mul)
	tb.ui:Cursor()
	tb.ui:Render(self:LocalToWorld(Vector(3.2, -0.5, 12)), self:LocalToWorldAngles(Angle(0, 180, 0)), 0.022)
end

function ENT:Think()
end

function ENT:OnRemove()
	SafeRemoveEntity(self.BackSide)
end