-- ==================================================================================================================== --
--															--
--	File			PieChart.lua										--
--															--
--															--
--	Author			Zarnivoop, Luckycire(maintainer)		| Version	   :	  7.0.0 |	--
--										| Curse-Project-ID :	 	|	--
--										| 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("Pie chart")


local libwindow	  = LibStub("LibWindow-1.1")
local libgraph    = LibStub("LibGraph-2.0")
local media	  = LibStub("LibSharedMedia-3.0")


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


local hue
local goldenRatio = 0.618033988749895
local saturation  = 0.3
local value	  = 0.95


mod.name	  = L["Pie chart"]
mod.description   = emptyLines .. blankChars .. "\124cFF00FF00" .. L["Pie chart"] .. "\n" .. blankChars ..  "|cffffffff" .. L["The pie chart; this can be visually customized."]


Skada:AddDisplaySystem("pie", mod)




function mod:OnInitialize()

	self.db = LibStub("AceDB-3.0"):New("SkadaGraphsDB")
end




function mod:HandlePieSelection(win, num)


end




--  =============
--  | Pie Chart |
--  =============
function mod:Create(win)

	if not win.frame then

		hue = math.random()


		if self.db.global.piesaturation then saturation = self.db.global.piesaturation end


		win.colorcache = {}


		--  ===============================
		--  | Pie Chart: backdrop (frame) |
		--  ===============================
		local backdropFrameInfo =

				{

					bgFile	 = media:Fetch("background", "Solid"),
				 	tile	 = false,
				 	edgeSize = 0,
					insets	 = { left = 0, right = 0, top = 0, bottom = 0 },
				}


		--  ====================
		--  | Pie Chart: frame |
		--  ====================
		win.frame     = CreateFrame("Frame", win.db.name .. "PieChartFrame", UIParent, "BackdropTemplate")
		win.frame.win = win


		win.frame:SetMovable(true)
		win.frame:SetClampedToScreen(true)
		win.frame:Size(550, 200)

		win.frame:SetBackdrop(backdropFrameInfo)


		win.frame:SetBackdropBorderColor(1.0, 0.0, 0.0)


		if self.db.global.piebgcolor then

			win.frame:SetBackdropColor(self.db.global.piebgcolor.r or 0, self.db.global.piebgcolor.g or 0, self.db.global.piebgcolor.b or 0, self.db.global.piebgcolor.a or 0.83)
		else

			self.db.global.piebgcolor = { r, g, b, a }
			win.frame:SetBackdropColor(0, 0, 0, 0.83)
		end


		win.frame:SetPoint("TOPLEFT", UIParent, "CENTER", 0, 0)
		win.frame:EnableMouse()


		win.frame:SetScript("OnMousedown",

						function(f, button)

							if button == "RightButton" then	win:RightClick() end
						end

				   )


		--  ===========================
		--  | Pie Chart: legend frame |
		--  ===========================
		win.frame.legendframe = CreateFrame("Frame", nil, win.frame)


		win.frame.legendframe:SetWidth(345)

		win.frame.legendframe:SetPoint("TOPRIGHT"   , win.frame, "TOPRIGHT"   , -10, -20)
		win.frame.legendframe:SetPoint("BOTTOMRIGHT", win.frame, "BOTTOMRIGHT", -10,  20)


		win.frame.legendframe.AddLegend     = Skada.AddLegend
		win.frame.legendframe.ClearLegends  = Skada.ClearLegends


		win.frame.legendframe.ClickLegend   = function(id, label, button)

								Skada.ClickRow(win.frame, win, id, label, button)
						      end


		win.frame.legendframe.EnterLegend   = function(id, label)

								Skada.EnterRow(win.frame, win, id, label)
						      end


		win.frame.legendframe.LeaveLegend   = function(id, label)

								Skada.LeaveRow(win.frame, win, id, label)
						      end


		win.frame.legendframe.AdjustLegends = Skada.AdjustLegends


		Skada.SetupLegendScrolling(win.frame.legendframe)


		win.frame.MakeResizable		    = Skada.MakeResizable
		win.frame.OnResizingInProgress	    = function(self)

								win.chart:SetWidth(min(win.frame:GetWidth()  - 140, win.frame:GetHeight()))
								win.chart:SetHeight(min(win.frame:GetWidth() - 140, win.frame:GetHeight()))

								win:UpdateDisplay()
								win.frame.legendframe:AdjustLegends()
						      end


		win.frame.OnResizingDone	    = function(self)

								win.db.width  = win.frame:GetWidth()
								win.db.height = win.frame:GetHeight()
						      end


		win.frame:MakeResizable()
		win.frame:SetResizeBounds(484, 198)


		--  =======================================
		--  | Pie Chart: backdrop (button header) |
		--  =======================================
		local backdropButtonInfo =

			{

				bgFile   = media:Fetch("statusbar", "Aluminium"),
			 	tile     = false,
			 	edgeSize = 0,
			 	insets   = { left = 0, right = 0, top = 0, bottom = 0 },
			}


		--  ============================
		--  | Pie Chart: button header |
		--  ============================
		win.header = CreateFrame("Button", nil, win.frame, "BackdropTemplate")


		win.header:SetHeight(24)


		win.header:SetPoint("BOTTOMLEFT" , win.frame, "TOPLEFT" , 0, 0)
		win.header:SetPoint("BOTTOMRIGHT", win.frame, "TOPRIGHT", 0, 0)


		win.header:SetScript("OnMouseDown",

						function()

							win.frame:StartMoving()
						end

				    )


		win.header:SetScript("OnMouseUp",

						function()

							win.frame:StopMovingOrSizing()
							libwindow.SavePosition(win.frame)
						end

				    )


		win.header:SetBackdrop(backdropButtonInfo)


		win.header:SetBackdropBorderColor(1.0, 0.0, 0.0)
		win.header:SetBackdropColor(0, 0, 1, 0.2)


		if self.db.global.pieheaderbg then
 
			win.header:SetBackdropColor(self.db.global.pieheaderbg.r or 0.1, self.db.global.pieheaderbg.g or 0.1, self.db.global.pieheaderbg.b or 0.3, self.db.global.pieheaderbg.a or 0.8)
		else

			self.db.global.pieheaderbg = { r, g, b, a }
			win.header:SetBackdropColor(0.1, 0.1, 0.3, 0.8)
		end


		win.header:SetText(win.db.name)


		--  ===================
		--  | Pie Chart: font |
		--  ===================
		local titleFont = CreateFont("TitleFont")


		titleFont:SetFont(media:Fetch('font', win.db.barfont), win.db.barfontsize, win.db.barfontflags)


		win.header:SetNormalFontObject(titleFont)


		win.header.AddButton	 = Skada.AddButton
		win.header.AdjustButtons = Skada.AdjustButtons


		if not(self.db.global.pieenableheader) then self.db.global.pieenableheader = true end


		local size = min(win.frame:GetWidth() - 140, win.frame:GetHeight())
		local g    = libgraph:CreateGraphPieChart("PieChart", win.frame, "TOPLEFT", "TOPLEFT", 0, 0, size, size)


		g:SetSelectionFunc(function(f, n) self:HandlePieSelection(win, n) end)
		win.chart = g


		--  ======================
		--  | Pie Chart: buttons |
		--  ======================
		Skada:MenuButton(win, mod, reportButton, function() Skada:ShowPopup(win)        end, 20,  15, "Interface\\Buttons\\UI-StopButton"	  , "Interface\\Buttons\\UI-StopButton")
		Skada:MenuButton(win, mod, reportButton, function() Skada:OpenReportWindow(win) end, 20,   0, "Interface\\Buttons\\UI-GuildButton-MOTD-Up", "Interface\\Buttons\\UI-GuildButton-MOTD-Up")
		Skada:MenuButton(win, mod, menuButton  , function() Skada:OpenMenu(win)         end, 20, -15, "Interface\\Buttons\\UI-OptionsButton"	  , "Interface\\Buttons\\UI-OptionsButton")
	end


	win.frame:Show()


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




function mod:Destroy(win)

	wipe(win.colorcache)

	win.colorcache = nil
	win.frame.legendframe:ClearLegends()

	hue = math.random()

	win.frame:Hide()

	win.frame      = nil
	win.chart      = nil
	win.header     = nil
end




function mod:SetTitle(win, title)

	win.header:SetText(title)
end




local function round(num)

	local mult = 10^(0)


	return math.floor(num * mult + 0.5) / mult
end




function mod:Update(win)

	local total = 0


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

		if data.id and not data.ignore then

			if data.value > 0 then total = total + data.value end
		end
	end


	win.chart:ResetPie()

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

		if data.id and not data.ignore then

			local color


			if win.colorcache[data.id] then

				color = win.colorcache[data.id]
			else

				hue   = hue + goldenRatio
				hue   = hue - (math.floor(hue))

				color = Skada.GenerateColor(hue, saturation, value)


				win.colorcache[data.id] = color
			end


			if data.value > 0 then win.chart:AddPie(round((data.value / math.max(0.000001, total)) * 100), { color[1], color[2], color[3] }) end


			if data.id ~= nil and data.valuetext ~= nil then

				data.spellid = (tostring(data.spellid  ) or  0)
				data.label   = data.label .. "|" .. data.valuetext .. "|" .. data.spellid


				win.frame.legendframe:AddLegend(data.id, data.label, color)
			end
		end
	end


	win.frame.legendframe:AdjustLegends()
	win.chart:CompletePie({ 0.2, 0.2, 0.4 })
end




function mod:Wipe(win)

	win.chart:ResetPie()
	win.frame.legendframe:ClearLegends()
end




function mod:Show(win)

	win.frame:Show()
end




function mod:Hide(win)

	win.frame:Hide()
end




function mod:IsShown(win)

	return win.frame:IsShown()
end




function mod:ApplySettings(win)

	if win.db.barslocked then

		win.header:EnableMouse(false)
		win.frame.resizebutton:Hide()
	else

		win.header:EnableMouse(true)
		win.frame.resizebutton:Show()
	end


	if self.db.global.pieenableheader then

		win.header:Show()
	else

		win.header:Hide()
	end


	if self.db.global.piebgcolor then

		if not self.db.global.piebgcolor.r then	self.db.global.piebgcolor.r =    0 end
		if not self.db.global.piebgcolor.g then	self.db.global.piebgcolor.g =    0 end
		if not self.db.global.piebgcolor.b then	self.db.global.piebgcolor.b =    0 end
		if not self.db.global.piebgcolor.a then	self.db.global.piebgcolor.a = 0.83 end


		win.frame:SetBackdropColor(self.db.global.piebgcolor.r or 0, self.db.global.piebgcolor.g or 0, self.db.global.piebgcolor.b or 0, self.db.global.piebgcolor.a or 0.83)
	end


	if self.db.global.pieheaderbg then

		if not self.db.global.pieheaderbg.r then self.db.global.pieheaderbg.r = 0.1 end
		if not self.db.global.pieheaderbg.g then self.db.global.pieheaderbg.g = 0.1 end
		if not self.db.global.pieheaderbg.b then self.db.global.pieheaderbg.b = 0.3 end
		if not self.db.global.pieheaderbg.a then self.db.global.pieheaderbg.a = 0.8 end


		win.header:SetBackdropColor(self.db.global.pieheaderbg.r or 0.1, self.db.global.pieheaderbg.g or 0.1, self.db.global.pieheaderbg.b or 0.3, self.db.global.pieheaderbg.a or 0.8)
	end


	local pieFontHeader = CreateFont("FontTitle")


	if not self.db.global.pieheaderfont	 then self.db.global.pieheaderfont      = "Accidental Presidency" end
	if not self.db.global.pieheaderfontsize	 then self.db.global.pieheaderfontsize  = 12			  end
	if not self.db.global.pieheaderfontflags then self.db.global.pieheaderfontflags = ""			  end


	pieFontHeader:SetFont(media:Fetch('font', self.db.global.pieheaderfont), self.db.global.pieheaderfontsize, self.db.global.pieheaderfontflags)


	win.header:SetNormalFontObject(pieFontHeader)


	if self.db.global.piesaturation then

		saturation = self.db.global.piesaturation
		wipe(win.colorcache)
	end
end




function mod:AddDisplayOptions(win, options)

	local db = self.db

     options.pieoptions =

			{

			  type  = "group",
			  name  = L["Pie"],
			  order = 1,

			  args  =

				{

			     pieoptions =

					{

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

					},

			pieenableheader =

					{

						   type = "toggle",
						   name = L["Enable header"],
						   desc = L["Enables/disables the header bar."],
						    get = function()

								  return db.global.pieenableheader
							  end,
						    set = function(win, showtotal)

								  db.global.pieenableheader = not db.global.pieenableheader
				         			  Skada:ApplySettings()
							  end,
						  order = 1,
					},

				  piebg =

					{

						   type = "color",
						   name = L["Background color"],
						   desc = L["Choose the background color for the pie chart."],
					       hasAlpha = true,
						    get = function(i)

								  return db.global.piebgcolor.r, db.global.piebgcolor.g, db.global.piebgcolor.b, db.global.piebgcolor.a
							  end,
						    set = function(i, r, g, b, a)

								  db.global.piebgcolor = { ["r"] = r, ["g"] = g, ["b"] = b, ["a"] = a }
								  Skada:ApplySettings()
							  end,
						  order = 2,

					},

			       headerbg =

					{

						   type = "color",
						   name = L["Background color"],
						   desc = L["Choose the background color for the header."],
					       hasAlpha = true,
						    get = function(i)

								  return db.global.pieheaderbg.r, db.global.pieheaderbg.g, db.global.pieheaderbg.b, db.global.pieheaderbg.a
							  end,
						    set = function(i, r, g, b, a)

								  db.global.pieheaderbg = { ["r"] = r, ["g"] = g, ["b"] = b, ["a"] = a }
								  Skada:ApplySettings()
							  end,
						  order = 3,

					},

			  pieheaderfont =

					{

						   type = 'select',
					  dialogControl = 'LSM30_Font',
						   name = L["Font"],
						   desc = L["The font used by the header."],
						 values = AceGUIWidgetLSMlists.font,
						    get = function()

								  return db.global.pieheaderfont or 12
							  end,
						    set = function(win,key)

								  db.global.pieheaderfont = key
								  Skada:ApplySettings()
							  end,
						  order = 4,

					},

		      pieheaderfontsize =

					{

						   type = "range",
						   name = L["Font size"],
						   desc = L["The font size used by the header."],
						    min = 12,
						    max = 40,
						   step = 1,
						    get = function()

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

								  db.global.pieheaderfontsize = size
								  Skada:ApplySettings()
							  end,
						  order = 5,

					},

		     pieheaderfontflags =

					{

						   type = 'select',
						   name = L["Font flags"],
						   desc = L["Sets the font flags for the header."],
						 values = { [""] = L["None"], ["OUTLINE"] = L["Outline"], ["THICKOUTLINE"] = L["Thick outline"],
								    ["MONOCHROME"] = L["Monochrome"], ["OUTLINEMONOCHROME"] = L["Outlined monochrome"] },
						    get = function()

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

								  db.global.pieheaderfontflags = key
								  Skada:ApplySettings()
							  end,
						  order = 6,

					},

				  piebg =

					{

						   type = "range",
						   name = L["Color saturation"],
						   desc = L["Choose the color saturation value used by the pie chart."],
						    min = 0,
						    max = 1,
						   step = 0.05,
						    get = function()

								  return db.global.piesaturation
							  end,
						    set = function(win, saturation)

								  db.global.piesaturation = saturation
								  Skada:ApplySettings()
							  end,
						  order = 7,
					},
				}
			}
end