-- ==================================================================================================================== --
--															--
--	File			BrokerDisplay										--
--															--
--															--
--	Author			Zarnivoop					| Version	   :	 10.0.2 |	--
--										| Curse-Project-ID :	 694380 |	--
--										| License	   :	  MIT/X |	--
--															--
--											| Basis, thx	|		--
--															--
--															--
--				Baltha						| Version	   :	 11.2.0 |	--
--										| Curse-Project-ID :	1188318 |	--
--										| License	   :	  MIT/X |	--
--															--
--											| Revision	|		--
--															--
--															--
--	Path ( Revision )	"..\World of Warcraft\_retail_\Interface\AddOns\Skada\Misc\Changelog\ChangeLog.txt"	--
--															--
-- ==================================================================================================================== --


local _, Skada	 = ...


local L		 = LibStub("AceLocale-3.0"):GetLocale("Skada", false)
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 blankChars = string.rep(" ", 6)
local ttactive   = false

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


SkadaMetaTitle   = SkadaMetaTitle or ""


Skada:AddDisplaySystem("broker", mod)




local function sortDataset(win)

	table.sort(win.dataset,

			function (a, b)

				if not a or a.value == nil then

					return false
				elseif not b or b.value == nil then

					return true
				else

					return a.value > b.value
				end
			end

		  )

end




function mod:OnInitialize()

end




local function clickHandler(win, frame, button)

	if not win.obj then return end


	if button=="LeftButton" or button=="RightButton" then

		Skada:OpenMenu(win)
	end
end




local function formatValue(win, data)

	return data.valuetext
end




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:SetSize(win.db.width or 200, win.db.height or 30)
		win.frame:SetPoint("CENTER", 0, 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("OnMouseUp",

					function(frame, button)
						clickHandler(win, frame, button)

					end

				   )


		win.frame:SetScript("OnDragStart",

					function(frame)

						if not win.db.barslocked then

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

				   )


		win.frame:SetScript("OnDragStop",

					function(frame)

						frame:StopMovingOrSizing()
						frame.isDragging = false

						libwindow.SavePosition(frame)
					end

				   )


		if not win.obj then

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

								{
									   type = "data source",
									   text = "",

									OnClick = function(frame, button)

											  clickHandler(win, frame, button)
										  end

								}

						   )

		end


		mod:ApplySettings(win)
	end


	local menu = CreateFrame("Button", "InlineFrameMenuButton", win.frame, "BackdropTemplate")

	menu:ClearAllPoints()
	menu:SetSize(16, 16)
	menu:SetNormalTexture("Interface\\Buttons\\UI-OptionsButton")
	menu:SetHighlightTexture("Interface\\Buttons\\UI-OptionsButton", "ADD")
	menu:SetAlpha(0.5)


	menu:RegisterForClicks("LeftButtonUp", "RightButtonUp")


	menu:SetBackdropColor(win.db.title.textcolor.r,win.db.title.textcolor.g,win.db.title.textcolor.b,win.db.title.textcolor.a)
	menu:SetPoint("BOTTOMLEFT", win.frame, "BOTTOMLEFT", 6, win.db.height / 2 - 8)


	menu:SetFrameLevel(9)
	menu:SetPoint("CENTER")
	menu:SetBackdrop(skadamenubuttonbackdrop)


	menu:SetScript("OnClick",

			       function()

				       Skada:OpenMenu(window)
			       end

		      )


	win.frame.skadamenubutton = title
	win.frame.menu		  = menu
	win.frame.win		  = win


	win.frame:EnableMouse(true)

	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)

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


	sortDataset(win)


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

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


		if win.selectedset == "current" 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 = "", "", ""


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

		unitSeg = smtSegment
		unitVal = tostring(win.metadata.maxvalue)


		local data = win.dataset[1]


		if data.id or modeChanged then

			local label =  unitMod .. "  " .. unitSeg .. blankChars .. unitNam .. " " .. (formatValue(win, data) or "")


			if win.obj	   then	win.obj.text = label	       end
			if win.db.useframe then	win.frame.title:SetText(label) end
		end
	end
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:SetSize(win.db.width or 200, win.db.height or 30)



		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(self, options)

	local db     = self.db


	options.main =

			{

			   type = "group",
			   name = "Datatext",
			  order	= function()

					  if GetLocale() == "deDE" then return 4 end
					  if GetLocale() == "enUS" then return 5 end
				  end,

			  args  =

				{

			     dfoptions =

					{

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

						  order = 0,

					},

			       useframe =

					{

						   type = 'toggle',
						   name = "Use frame",
						   desc = "Shows a standalone frame. Not needed if you are using an LDB display provider such as Titan Panel or ChocolateBar.",
						    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',
						   name = "\124cFF00FF00" .. L["Bar font"],
						   desc = L["The font used by all bars."],
					  dialogControl = 'LSM30_Font',
						 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
