-- ==================================================================================================================== --
--															--
--	File			BrokerDisplay.lua									--
--															--
--															--
--	Author			Zarnivoop						| Basis, thx	|		--
--															--
--										| Version	   :	 12.0.1 |	--
--										| Curse-Project-ID :	  17718 |	--
--										| Wago-ID	   :   Q6aEVa6W |	--
--										| License	   :	  MIT/X |	--
--															--
--															--
--				Baltha							| Revision	|		--
--										| Version	   :	 12.0.5 |	--
--										| Curse-Project-ID :	1188318 |	--
--										| License	   :	  MIT/X |	--
--															--
--															--
--										| Initial Version  : 2024-11-18 |	--
--										| Current Version  : 2026-05-17 |	--
--										|		   : Release	|	--
--															--
--															--
--	Path ( Revision )	"..\World of Warcraft\_retail_\Interface\AddOns\Skada\Misc\Changelog\ChangeLog.txt"	--
--															--
-- ==================================================================================================================== --


local _, Skada	  = ...


local L		  = LibStub("AceLocale-3.0"):GetLocale("Skada", true)
local mod	  = Skada:NewModule("Data text")


local ldb	  = LibStub:GetLibrary("LibDataBroker-1.1")
local libwindow	  = LibStub("LibWindow-1.1")
local media	  = LibStub("LibSharedMedia-3.0")


local emptyLines  = string.rep("\n", 2)


local blankChars1 = string.rep(" " , 2)
local blankChars2 = string.rep(" " , 6)


local ttactive    = false


mod.name	  = L["Data text"]
mod.description   = emptyLines .. blankChars2 .. "\124cFF00FF00" .. L["Data text"] .. "\n" .. blankChars2 .. "|cffffffff" .. L["Acts as an LDB data feed and can be integrated in any LDB display."]



Skada:AddDisplaySystem("broker", mod)


local function sortDataset(win)

	table.sort(win.dataset,

			function (a, b)

				if not a or not a.id then

					return false
				elseif not b or not b.id then

					return true
				else

					return Skada:SafeNumber(a.value) > Skada:SafeNumber(b.value)
				end
			end

		  )

end




local function formatLabel(win, data)

	if not data then return "" end


	if win.db.isusingclasscolors and data.class and RAID_CLASS_COLORS[data.class] then

		return string.format("|c%s%s|r", RAID_CLASS_COLORS[data.class].colorStr, data.label or "")
	else

		return string.format("%s", data.label or "")
	end
end




local function formatValue(win, data)

	if not data then return "" end


	if data.valuetext then

		return string.format("%s", data.valuetext)
	else

		if data.valueText1 and data.valueText2 then

			return string.format("%s %s %s", blankChars1 .. data.valueText3 , blankChars2 .. data.valueText1, blankChars2 .. data.valueText2)
		else

			return string.format("%s", data.valueText1 or "")
		end
	end
end




local function clickHandler(win, frame, button)

	if not win.obj then return end
end




local function tooltipHandler(win, tooltip)

	if win.db.useframe then	Skada:SetTooltipPosition(tooltip, win.frame) end


	local color = win.db.textcolor


	tooltip:AddLine(win.metadata.title)
	tooltip:AddLine(" ")


	sortDataset(win)


	if #win.dataset > 0 then

		for i, data in ipairs(win.dataset) do

			if data.id and not data.ignore and i < 30 then

				local label = formatLabel(win, data)
				local value = formatValue(win, data)


				if win.metadata.showspots and Skada.db.profile.showranks then label = (("%2u. %s"):format(i, label)) end


				tooltip:AddDoubleLine(label or "", value or "", color.r, color.g, color.b, color.r, color.g, color.b)
			end
		end
	end


	tooltip:Show()
end


local ttactive = false


function mod:Create(win, isnew)

	if not win.frame then

		local winName = win.db.name .. "BrokerFrame"


		win.frame = CreateFrame("Frame", winName, UIParent, "BackdropTemplate")

		win.frame:SetHeight(win.db.height or 30)
		win.frame:SetWidth(win.db.width or 520)
		win.frame:SetPoint("LEFT", 30, 0)


		libwindow.RegisterConfig(win.frame, win.db)


		if isnew then

			libwindow.SavePosition(win.frame)
		else

			libwindow.RestorePosition(win.frame)
		end


		local title = win.frame:CreateFontString("frameTitle", "OVERLAY", "ChatFontNormal")


		title:SetPoint("LEFT", 30, 0)


		win.frame.title = title

		win.frame:EnableMouse(true)
		win.frame:SetMovable(true)
		win.frame:RegisterForDrag("LeftButton")


		win.frame:SetScript("OnEnter",

					function(frame)

						tooltipHandler(win, GameTooltip)
					end

				   )


		win.frame:SetScript("OnLeave",

					function(frame)

						GameTooltip:Hide()
					end

				   )



		win.frame:SetScript("OnDragStart",

					function(frame)

						if not win.db.barslocked then

							GameTooltip:Hide()


							frame.isDragging = true
							frame:StartMoving()
						end
					end

				   )



		win.frame:SetScript("OnDragStop",

					function(frame)

						frame:StopMovingOrSizing()
						frame.isDragging = false


						libwindow.SavePosition(frame)
					end

				   )

	end


	if not win.obj then

		win.obj = ldb:NewDataObject('Skada: ' .. win.db.name,

							{

									 type = "data source"					,
									 text = ""						,
								OnTooltipShow = function(tooltip)

											tooltipHandler(win, tooltip)
										end

							}
					   )
	end


	Skada:MenuButton(win, mod, resetButton, function() Skada:Reset()       end, 20,  10, "Interface\\Buttons\\UI-StopButton"   , "Interface\\Buttons\\UI-StopButton")
	Skada:MenuButton(win, mod, menuButton , function() Skada:OpenMenu(win) end, 20, -10, "Interface\\Buttons\\UI-OptionsButton", "Interface\\Buttons\\UI-OptionsButton")


	mod:ApplySettings(win)
end




function mod:IsShown(win)

	return win.frame:IsShown()
end




function mod:Show(win)

	if win.db.useframe then	win.frame:Show() end
end




function mod:Hide(win)

	if win.db.useframe then	win.frame:Hide() end
end




function mod:Destroy(win)

	win.obj.text = " "
	win.obj = nil


	win.frame:Hide()
	win.frame = nil
end




function mod:Wipe(win)

	win.text = " "
end




function mod:SetTitle(win, title)

end




function mod:Update(win)

	local db = win.db


	if win.obj then	win.obj.text = "" end


	if win.db.mode ~= nil and #win.dataset > 0 then

		local data = win.dataset[1]


		local unitName, unitClassFilename, smtModus, oldSegment, smtSegment, modeChanged = (data.label or UnitName("player")), (data.class or UnitClassBase("player")), win.db.mode, "", "", false


		if win.selectedset == "current" or nil then smtSegment = L["Current"] end
		if win.selectedset == "total"          then smtSegment = L["Total"]   end


		do

			if SkadaMetaTitle ~= smtModus then SkadaMetaTitle = smtModus end


			modeChanged = true
		end


		local unitMod, unitNam, unitSeg = "", "", ""


		unitNam = "|c" .. RAID_CLASS_COLORS[unitClassFilename].colorStr .. unitName .. "|r"
		unitSeg = smtSegment
		unitMod = "|c" .. RAID_CLASS_COLORS[unitClassFilename].colorStr .. smtModus .. "|r"


		local labelText = unitNam .. blankChars1 .. unitSeg .. blankChars2 .. unitMod


		if data and data.id then


			local fullText  = string.format("%s %s", labelText, formatValue(win, data))


			if win.obj then

				pcall(function() win.obj.text = fullText end)
			end



			if win.db.useframe then

				win.frame.title:SetText(fullText)
			end
		elseif	#data == 0 then

			local fullText  = string.format("%s %s", labelText, "")


			if win.obj then

				pcall(function() win.obj.text = fullText end)
			end



			if win.db.useframe then

				win.frame.title:SetText(fullText)
			end


			if win.obj then

				pcall(function() win.obj.text = fullText end)
			end
		end
	end
end




function mod:OnInitialize()

end




function mod:ApplySettings(win)

	if win.db.useframe then

		local title = win.frame.title
		local db    = win.db


		win.frame:SetMovable(not win.db.barslocked)
		win.frame:SetHeight(win.db.height or 30)
		win.frame:SetWidth(win.db.width or 520)


		local fbackdrop    = {}


		fbackdrop.bgFile   = media:Fetch("background", db.background.texture)
		fbackdrop.tile	   = db.background.tile
		fbackdrop.tileSize = db.background.tilesize


		win.frame:SetBackdrop(fbackdrop)
		win.frame:SetBackdropColor(db.background.color.r,db.background.color.g,db.background.color.b,db.background.color.a)


		Skada:ApplyBorder(win.frame, db.background.bordertexture, db.background.bordercolor, db.background.borderthickness)


		title:SetTextColor(db.textcolor.r,db.textcolor.g,db.textcolor.b,db.textcolor.a)
		title:SetFont(media:Fetch('font', db.barfont), db.barfontsize, db.barfontflags)
		title:SetText(win.metadata.title or "Skada")
		title:SetWordWrap(false)
		title:SetJustifyH("CENTER")
		title:SetJustifyV("MIDDLE")
		title:SetHeight(win.db.height or 30)


		win.frame:SetScale(db.scale)
		win.frame:SetFrameStrata(db.strata)
	else

		win.frame:Hide()
	end


	self:Update(win)
end




function mod:AddDisplayOptions(win, options)

	local db = win.db


	   options.main =

			{

					   type = "group"																			,
					   name = "Datatext"																			,
					  order = 2																				,

					   args =

						{

							      dfoptions =

									{

											   type = "description"													,
											   name = "\124cnNORMAL_FONT_COLOR:" .. L["Options: data text"] .. " " ..  "|cffffffff" .. db.name .. emptyLines	,
											  order = 0

									}	,

							       useframe =

									{

											   type = 'toggle'													,
											   name = L["Use frame"]												,
											   desc = L["Shows a standalone frame. Not needed if you are using an LDB display provider."]				,
											    get = function()

													  return db.useframe
												  end														,
											    set = function(win,key)

													  db.useframe = key


													  Skada:ApplySettings()
												  end														,
											  order = 1

									}	,

							 classcolortext =

									{

											   type = "toggle"													,
											   name = L["Class color text"]												,
											   desc = L["When possible, bar text will be colored according to player class."]					,
											    get = function()

													  return db.isusingclasscolors
												  end														,
											   set = function()

													 db.isusingclasscolors = not db.isusingclasscolors


													 Skada:ApplySettings()
												 end														,
											 order = 2

									}	,

								  color =

									{

											   type = "color"													,
											   name = L["Text color"]												,
											   desc = L["Choose the default color."]										,
										       hasAlpha = true														,
											    get = function(i)

													  local c = db.textcolor


													  return c.r, c.g, c.b, c.a
												  end														,
											    set = function(i, r,g,b,a)

													  db.textcolor = {["r"] = r, ["g"] = g, ["b"] = b, ["a"] = a}


													  Skada:ApplySettings()
												  end														,
											  order = 3

									}	,

								barfont =

									{

											   type = 'select'													,
										  dialogControl = 'LSM30_Font'													,
											   name = "\124cFF00FF00" .. L["Bar font"]										,
											   desc = L["The font used by all bars."]										,
											 values = AceGUIWidgetLSMlists.font											,
											    get = function()

													  return db.barfont
												  end														,
											    set = function(win,key)

													  db.barfont = key


													  Skada:ApplySettings()
												  end														,
											  order = 4

									}	,

							    barfontsize =

									{

											   type = "range"													,
											   name = "\124cFF00FF00" .. L["Bar font size"]										,
											   desc = L["The font size of all bars."]										,
											    min = 7														,
											    max = 40														,
											   step = 1														,
											    get = function()

													  return db.barfontsize
												  end														,
											    set = function(win, size)

													  db.barfontsize = size


													  Skada:ApplySettings()
												  end														,
											  order = 5

									}	,

							   barfontflags =

									{
											   type = 'select'													,
											   name = "\124cFF00FF00" .. L["Font flags"]										,
											   desc = L["Sets the font flags."]											,
											 values =

												{

													   		    [""] = L["None"]									,
													   	     ["OUTLINE"] = L["Outline"]									,
													   	["THICKOUTLINE"] = L["Thick outline"]								,
														  ["MONOCHROME"] = L["Monochrome"]								,
													   ["OUTLINEMONOCHROME"] = L["Outlined monochrome"]

												}														,


											    get = function()

													  return db.barfontflags
												  end														,
											    set = function(win,key)

													  db.barfontflags = key


													  Skada:ApplySettings()
												  end														,
											  order = 6

									}
						}
			}


	options.window = Skada:FrameSettings(db, true)
end