TOOL.Category = "Construction"
TOOL.Name = "3D2DText"

local textBox = {}
local lineLabels = {}
local labels = {}
local sliders = {}
local fontSize = {}

for i = 1, 5 do
	TOOL.ClientConVar["text"..i] = ""
	TOOL.ClientConVar["size"..i] = 20
	TOOL.ClientConVar["r"..i] = 255
	TOOL.ClientConVar["g"..i] = 255
	TOOL.ClientConVar["b"..i] = 255
	TOOL.ClientConVar["a"..i] = 255
end

TOOL.Information = {
	{name = "left"},
	{name = "right"}
}

cleanup.Register("3d2dtexts")

if CLIENT then
	language.Add("tool.3d2dtext.name", "3D2DText")
	language.Add("tool.3d2dtext.desc", "Holographischer Effekt, welcher eigenkonfigurierten Text wiederspiegeln kann.")
	language.Add("tool.3d2dtext.left", "3D2DText erstellen/aktualisieren")
	language.Add("tool.3d2dtext.right", "3D2DText-Einstellungen kopieren")
	language.Add("max_3d2dtexts", "Maximale 3D2D Texte")
	language.Add("Undone_3D2D Text", "Undone 3D2D Text")
	language.Add("Cleanup_3d2dtexts", "3D2DTexts")
	language.Add("Cleaned_3d2dtexts", "Cleaned up all 3D2D Texts")
	language.Add("SBoxLimit_3d2dtexts", "You've hit the 3D2DText Limit!")
end

function TOOL:LeftClick(tr)
	local ent = tr.Entity
	if IsValid(ent) and ent:IsPlayer() then return false end
	local ply = self:GetOwner()
	local text_exists
	for i = 1, 5 do
		if (tonumber(utf8.len(tostring(self:GetClientInfo("text"..i)))) or 0) > 0 then
			text_exists = true
			break
		end
	end
	if !text_exists then ply:PrintMessage(4, "Kein Text eingestellt!") return false end
	if CLIENT then return true end
	if IsValid(ent) and ent:GetClass() == "3d2dtext" then
		for i = 1, 5 do
			local text = tostring(self:GetClientInfo("text"..i)) or ""
			local size = math.Clamp(self:GetClientNumber("size"..i), 20, 100)
			ent:SetLine(i, text, Color(self:GetClientNumber("r"..i), self:GetClientNumber("g"..i), self:GetClientNumber("b"..i), self:GetClientNumber("a"..i)), size)
		end
		ent:Broadcast()
		return true
	end
	if !self:GetWeapon():CheckLimit("3d2dtexts") then return false end
	local text3d2d = ents.Create("3d2dtext")
	if !IsValid(text3d2d) then return false end
	text3d2d:SetPos(tr.HitPos)
	local angle = tr.HitNormal:Angle()
	angle:RotateAroundAxis(tr.HitNormal:Angle():Right(), -90)
	angle:RotateAroundAxis(tr.HitNormal:Angle():Forward(), 90)
	text3d2d:SetAngles(angle)
	text3d2d:Spawn()
	text3d2d:Activate()
	for i = 1, 5 do
		local text = tostring(self:GetClientInfo("text"..i)) or ""
		local size = math.Clamp(self:GetClientNumber("size"..i), 20, 100)
		text3d2d:SetLine(i, text, Color(self:GetClientNumber("r"..i), self:GetClientNumber("g"..i), self:GetClientNumber("b"..i), self:GetClientNumber("a"..i)), size)
	end
	undo.Create("3D2D Text")
		undo.AddEntity(text3d2d)
		undo.SetPlayer(ply)
	undo.Finish()
	ply:AddCount("3d2dtexts", text3d2d)
	ply:AddCleanup("3d2dtexts", text3d2d)
	return true
end

function TOOL:RightClick(tr)
	local ent = tr.Entity
	if !IsValid(ent) or ent:GetClass() != "3d2dtext" then return false end
	if CLIENT then return true end
	local ply = self:GetOwner()
	for i = 1, 5 do
		if ent.lines[i]["text"] == "" then
			ply:ConCommand("3d2dtext_text"..i.." \"\"")
		else
			ply:ConCommand("3d2dtext_text"..i.." \""..ent.lines[i]["text"].."\"")
		end
		ply:ConCommand("3d2dtext_r"..i.." "..ent.lines[i]["color"].r)
		ply:ConCommand("3d2dtext_g"..i.." "..ent.lines[i]["color"].g)
		ply:ConCommand("3d2dtext_b"..i.." "..ent.lines[i]["color"].b)
		ply:ConCommand("3d2dtext_a"..i.." "..ent.lines[i]["color"].a)
		ply:ConCommand("3d2dtext_size"..i.." "..ent.lines[i]["size"])
	end
	return true
end

local fonts_table = {}
local function CreateFont(size)
	if !fonts_table[size] then
		fonts_table[size] = true
		surface.CreateFont("3D2DText_Preview_"..size, {font = "coolvetica", size = size, weight = 400, antialias = false, outline = true})
	end
end

local ConVarsDefault = TOOL:BuildConVarList()
local resetall
local resetline
function TOOL:BuildCPanel()
	self:AddControl("Header", {Text = "#tool.3d2dtext.name", Description = "#tool.3d2dtext.desc"})
	self:AddControl("ComboBox", {MenuButton = 1, Folder = "3d2dtext", Options = {["#preset.default"] = ConVarsDefault}, CVars = table.GetKeys(ConVarsDefault)})
	resetall = vgui.Create("DButton", resetbuttons)
	resetall:SetSize(100, 25)
	resetall:SetText("Alles zurücksetzen")
	resetall.DoClick = function()
		local menu = DermaMenu()
		menu:AddOption("Farben zurücksetzen", function()
			for i = 1, 5 do
				RunConsoleCommand("3d2dtext_r"..i, 255)
				RunConsoleCommand("3d2dtext_g"..i, 255)
				RunConsoleCommand("3d2dtext_b"..i, 255)
				RunConsoleCommand("3d2dtext_a"..i, 255)
			end
		end)
		menu:AddOption("Größen zurücksetzen", function()
			for i = 1, 5 do
				RunConsoleCommand("3d2dtext_size"..i, 20)
				sliders[i]:SetValue(20)
			end
		end)
		menu:AddOption("Texte zurücksetzen", function()
			for i = 1, 5 do
				RunConsoleCommand("3d2dtext_text"..i, "")
				textBox[i]:SetValue("")
			end
		end)
		menu:AddSpacer()
		menu:AddOption("Alles zurücksetzen", function()
			for i = 1, 5 do
				RunConsoleCommand("3d2dtext_r"..i, 255)
				RunConsoleCommand("3d2dtext_g"..i, 255)
				RunConsoleCommand("3d2dtext_b"..i, 255)
				RunConsoleCommand("3d2dtext_a"..i, 255)
				RunConsoleCommand("3d2dtext_size"..i, 20)
				sliders[i]:SetValue(20)
				RunConsoleCommand("3d2dtext_text"..i, "")
				textBox[i]:SetValue("")
			end
		end)
		menu:Open()
	end
	self:AddItem(resetall)
	resetline = vgui.Create("DButton")
	resetline:SetSize(100, 25)
	resetline:SetText("Zeile zurücksetzen")
	resetline.DoClick = function()
		local menu = DermaMenu()
		for i = 1, 5 do
			menu:AddOption("Zeile "..i, function()
				RunConsoleCommand("3d2dtext_r"..i, 255)
				RunConsoleCommand("3d2dtext_g"..i, 255)
				RunConsoleCommand("3d2dtext_b"..i, 255)
				RunConsoleCommand("3d2dtext_a"..i, 255)
				RunConsoleCommand("3d2dtext_size"..i, 20)
				sliders[i]:SetValue(20)
				RunConsoleCommand("3d2dtext_text"..i, "")
				textBox[i]:SetValue("")
			end)
		end
		menu:AddSpacer()
		menu:AddOption("Alle Zeilen zurücksetzen", function()
			for i = 1, 5 do
				RunConsoleCommand("3d2dtext_r"..i, 255)
				RunConsoleCommand("3d2dtext_g"..i, 255)
				RunConsoleCommand("3d2dtext_b"..i, 255)
				RunConsoleCommand("3d2dtext_a"..i, 255)
				RunConsoleCommand("3d2dtext_size"..i, 20)
				sliders[i]:SetValue(20)
				RunConsoleCommand("3d2dtext_text"..i, "")
				textBox[i]:SetValue("")
			end
		end)
		menu:Open()
	end
	self:AddItem(resetline)
	for i = 1, 5 do
		fontSize[i] = math.Clamp(GetConVar("3d2dtext_size"..i):GetInt(), 20, 100)
		CreateFont(fontSize[i])
		local text = GetConVar("3d2dtext_text"..i):GetString()
		labels[i] = self:AddControl("Label", {Text = #text >= 1 and text or "Zeile "..i, Description = "Zeile "..i})
		labels[i]:SetFont("3D2DText_Preview_"..fontSize[i])
		labels[i]:SetAutoStretchVertical(true)
		labels[i]:SetText("")
		labels[i]:SetDisabled(true)
		labels[i].Think = function()
			local text = textBox[i]:GetValue()
			labels[i]:SetText(#string.Trim(text) >= 1 and text or "Zeile "..i)
			labels[i]:SetColor(Color(GetConVar("3d2dtext_r"..i):GetInt(), GetConVar("3d2dtext_g"..i):GetInt(), GetConVar("3d2dtext_b"..i):GetInt(), GetConVar("3d2dtext_a"..i):GetInt()))
		end
		self:AddControl("Color", {Label = "Schriftfarbe", Red = "3d2dtext_r"..i, Green = "3d2dtext_g"..i, Blue = "3d2dtext_b"..i, Alpha = "3d2dtext_a"..i, ShowHSV = 1, ShowRGB = 1, Multiplier = 255})
		sliders[i] = vgui.Create("DNumSlider")
		sliders[i]:SetText("Schriftgröße")
		sliders[i]:SetDark(true)
		sliders[i]:SetMinMax(20, 100)
		sliders[i]:SetValue(20)
		sliders[i]:SetDecimals(0)
		sliders[i]:SetConVar("3d2dtext_size"..i)
		sliders[i]:SetValue(GetConVar("3d2dtext_size"..i))
		sliders[i].OnValueChanged = function(panel, value)
			fontSize[i] = math.Clamp(tonumber(math.floor(value)), 20, 100)
			CreateFont(fontSize[i])
			labels[i]:SetFont("3D2DText_Preview_"..fontSize[i])
			labels[i]:SetHeight(fontSize[i])
		end
		self:AddItem(sliders[i])
		textBox[i] = vgui.Create("DTextEntry")
		textBox[i]:SetUpdateOnType(true)
		textBox[i]:SetEnterAllowed(true)
		textBox[i]:SetConVar("3d2dtext_text"..i)
		textBox[i]:SetValue(GetConVar("3d2dtext_text"..i):GetString())
		self:AddItem(textBox[i])
	end
end