local GlobalAddonName, BH = ...

BH.Options = {}

local BHLib,L = BH.lib,BH.L

------------------------------------------------------------
--------------- New Options --------------------------------
------------------------------------------------------------

local OptionsFrameName = "BHOptionsFrame"
local Options = BHLib:Template("BHBWInterfaceFrame",UIParent)
_G[OptionsFrameName] = Options

BH.Options.Frame = Options

Options:Hide()
Options:SetPoint("CENTER",0,0)
Options:SetSize(750,650)
Options.HeaderText:SetText("BETA Heal")
Options:SetMovable(true)
--Options:SetBackdropColor(0.8,0,0,0.5) background color
Options:RegisterForDrag("LeftButton")
Options:SetScript("OnDragStart", function(self) self:StartMoving() end)
Options:SetScript("OnDragStop", function(self) self:StopMovingOrSizing() end)
Options:SetDontSavePosition(true)
Options.border = BH.lib.CreateShadow(Options,20)
Options.Width = 750

BHLib:ShadowInside(Options)

Options.bossButton:Hide()
Options.backToInterface:SetScript("OnClick",function ()
	BH.Options.Frame:Hide()
	InterfaceOptionsFrame:Show()
end)


Options.modulesList = BHLib:ScrollList(Options):Size(95-10,80-10):Point(10+5,-25-5):FontSize(11) -- pour la couleur du select voir exlib ligne 3180
Options.Frames = {}

Options:SetScript("OnShow",function(self)
	self.modulesList:Update()
	if Options.CurrentFrame and Options.CurrentFrame.AdditionalOnShow then
		Options.CurrentFrame:AdditionalOnShow()
	end
end)

function Options.modulesList:SetListValue(index)
	if Options.CurrentFrame then
		Options.CurrentFrame:Hide()
	end
	Options.CurrentFrame = Options.Frames[index]
	if Options.CurrentFrame.AdditionalOnShow then
		Options.CurrentFrame:AdditionalOnShow()
	end
	Options.CurrentFrame:Show()
end
function Options.modulesList:UpdateAdditional()
	if (self:GetHeight() / 16 - #self.L) > 0 then
		self.Frame.ScrollBar:Hide()
		self.Frame.C:SetWidth( self.Frame:GetWidth() )
	else
		self.Frame.ScrollBar:Show()
		self.Frame.C:SetWidth( self.Frame:GetWidth() - 16 )
	end
end

function BH.Options:Add(moduleName,frameName)
	local self = CreateFrame("Frame",OptionsFrameName..moduleName,Options)
	self:SetSize(600,615)
	self:SetPoint("TOPLEFT",100,-25)
	
	local pos = #Options.Frames + 1
	Options.modulesList.L[pos] = frameName or moduleName
	Options.Frames[pos] = self
	
	if Options:IsShown() then
		Options.modulesList:Update()
	end
	
	self:Hide()
	
	return self
end

function BH.Options:AddIcon(moduleName,icon)
	Options.modulesList.IconsRight = Options.modulesList.IconsRight or {}
	for i=1,#Options.modulesList.L do
		if Options.modulesList.L[i] == moduleName then
			Options.modulesList.IconsRight[i] = icon
			break
		end
	end
end

local OptionsFrame = BH.Options:Add("BETA Heal")
Options.modulesList:SetListValue(1)
Options.modulesList.selected = 1
Options.modulesList:Update()

------------------------------------------------------------

BH.Options.InBlizzardInterface = CreateFrame( "Frame", nil )
BH.Options.InBlizzardInterface.name = "BETA Heal"
InterfaceOptions_AddCategory(BH.Options.InBlizzardInterface)
BH.Options.InBlizzardInterface:Hide()

BH.Options.InBlizzardInterface:SetScript("OnShow",function (self)
	if InterfaceOptionsFrame:IsShown() then
		InterfaceOptionsFrame:Hide()
	end
	BH.Options:Open()
	self:SetScript("OnShow",nil)
end)

BH.Options.InBlizzardInterface.button = BHLib:Button(BH.Options.InBlizzardInterface,"BETA Heal",0):Size(400,25):Point("TOP",0,-100):OnClick(function ()
	if InterfaceOptionsFrame:IsShown() then
		InterfaceOptionsFrame:Hide()
	end
	BH.Options:Open()
end)

------------------------------------------------------------

Options.scale = BHLib:Slider(Options):_Size(70,8):Point("TOPRIGHT",-45,-5):Range(50,200,true):OnShow(function(self)
	VBH.Addon.Scale = tonumber(VBH.Addon.Scale or "1") or 1
	VBH.Addon.Scale = max( min( VBH.Addon.Scale,2 ),0.5)

	self:SetTo((VBH.Addon.Scale or 1)*100):Scale(1 / (VBH.Addon.Scale or 1)):OnChange(function(self,event) 
		if self.disable then
			self:SetTo(100)
			self.tooltipText = L.bossmodsscale.."|n100%|n"..L.SetScaleReset
			return
		end
		event = floor(event + 0.5)
		VBH.Addon.Scale = event / 100
		BH.F.SetScaleFixTR(Options,VBH.Addon.Scale)
		self:SetScale(1 / VBH.Addon.Scale)
		self.tooltipText = L.bossmodsscale.."|n"..event.."%|n"..L.SetScaleReset
		self:tooltipReload(self)
	end)
	self:SetScript("OnShow",nil)
	self.tooltipText = L.bossmodsscale.."|n"..((VBH.Addon.Scale or 1) * 100).."%|n"..L.SetScaleReset
	self:Point("TOPRIGHT",-45 * (VBH.Addon.Scale or 1),-5)
	Options:SetScale(VBH.Addon.Scale or 1)
end,true)

Options.scale:SetScript("OnMouseDown",function(self,button)
	if button == "RightButton" then
		self:SetTo(100)
		self.disable = true
	end
end)
Options.scale:SetScript("OnMouseUp",function(self,button)
	if button == "RightButton" then
		self.disable = nil
	end
	self:Point("TOPRIGHT",-45 * (VBH.Addon.Scale or 1),-5)
end)

----> Minimap Icon

local MiniMapIcon = CreateFrame("Button", "LibDBIcon10_ExorsusRaidTools", Minimap)
BH.MiniMapIcon = MiniMapIcon
MiniMapIcon:SetHighlightTexture("Interface\\Minimap\\UI-Minimap-ZoomButton-Highlight") 
MiniMapIcon:SetSize(32,32) 
MiniMapIcon:SetFrameStrata("MEDIUM")
MiniMapIcon:SetFrameLevel(8)
MiniMapIcon:SetPoint("CENTER", -12, -80)
MiniMapIcon:SetDontSavePosition(true)
MiniMapIcon:RegisterForDrag("LeftButton")
MiniMapIcon.icon = MiniMapIcon:CreateTexture(nil, "BACKGROUND")
MiniMapIcon.icon:SetTexture("Interface\\AddOns\\BH\\libs\\media\\MiniMap")
MiniMapIcon.icon:SetSize(32,32)
MiniMapIcon.icon:SetPoint("CENTER", 0, 0)
MiniMapIcon.border = MiniMapIcon:CreateTexture(nil, "ARTWORK")
MiniMapIcon.border:SetTexture("Interface\\Minimap\\MiniMap-TrackingBorder")
MiniMapIcon.border:SetTexCoord(0,0.6,0,0.6)
MiniMapIcon.border:SetAllPoints()
MiniMapIcon:RegisterForClicks("anyUp")
MiniMapIcon:SetScript("OnEnter",function(self) 
	GameTooltip:SetOwner(self, "ANCHOR_LEFT") 
	GameTooltip:AddLine("BETA Heal") 
	GameTooltip:AddLine(L.minimaptooltiplmp,1,1,1) 
	GameTooltip:AddLine(L.minimaptooltiprmp,1,1,1) 
	GameTooltip:Show() 
end)
MiniMapIcon:SetScript("OnLeave", function(self)    
	GameTooltip:Hide()
end)

local minimapShapes = {
	["ROUND"] = {true, true, true, true},
	["SQUARE"] = {false, false, false, false},
	["CORNER-TOPLEFT"] = {false, false, false, true},
	["CORNER-TOPRIGHT"] = {false, false, true, false},
	["CORNER-BOTTOMLEFT"] = {false, true, false, false},
	["CORNER-BOTTOMRIGHT"] = {true, false, false, false},
	["SIDE-LEFT"] = {false, true, false, true},
	["SIDE-RIGHT"] = {true, false, true, false},
	["SIDE-TOP"] = {false, false, true, true},
	["SIDE-BOTTOM"] = {true, true, false, false},
	["TRICORNER-TOPLEFT"] = {false, true, true, true},
	["TRICORNER-TOPRIGHT"] = {true, false, true, true},
	["TRICORNER-BOTTOMLEFT"] = {true, true, false, true},
	["TRICORNER-BOTTOMRIGHT"] = {true, true, true, false},
}

local function IconMoveButton(self)
	if self.dragMode == "free" then
		local centerX, centerY = Minimap:GetCenter()
		local x, y = GetCursorPosition()
		x, y = x / self:GetEffectiveScale() - centerX, y / self:GetEffectiveScale() - centerY
		self:ClearAllPoints()
		self:SetPoint("CENTER", x, y)
		VBH.Addon.IconMiniMapLeft = x
		VBH.Addon.IconMiniMapTop = y
	else
		local mx, my = Minimap:GetCenter()
		local px, py = GetCursorPosition()
		local scale = Minimap:GetEffectiveScale()
		px, py = px / scale, py / scale
		
		local angle = math.atan2(py - my, px - mx)
		local x, y, q = math.cos(angle), math.sin(angle), 1
		if x < 0 then q = q + 1 end
		if y > 0 then q = q + 2 end
		local minimapShape = GetMinimapShape and GetMinimapShape() or "ROUND"
		local quadTable = minimapShapes[minimapShape]
		if quadTable[q] then
			x, y = x*80, y*80
		else
			local diagRadius = 103.13708498985 --math.sqrt(2*(80)^2)-10
			x = math.max(-80, math.min(x*diagRadius, 80))
			y = math.max(-80, math.min(y*diagRadius, 80))
		end
		self:ClearAllPoints()
		self:SetPoint("CENTER", Minimap, "CENTER", x, y)
		VBH.Addon.IconMiniMapLeft = x
		VBH.Addon.IconMiniMapTop = y
	end
end

MiniMapIcon:SetScript("OnDragStart", function(self)
	self:LockHighlight()
	self:SetScript("OnUpdate", IconMoveButton)
	self.isMoving = true
	GameTooltip:Hide()
end)
MiniMapIcon:SetScript("OnDragStop", function(self)
	self:UnlockHighlight()
	self:SetScript("OnUpdate", nil)
	self.isMoving = false
end)

local function MiniMapIconOnClick(self, button)
	if button == "RightButton" then
		for _,func in pairs(BH.MiniMapMenu) do
			func:miniMapMenu()
		end
		BH.Options:UpdateModulesList()
		EasyMenu(BH.F.menuTable, BH.Options.MiniMapDropdown, "cursor", 10 , -15, "MENU")
	elseif button == "LeftButton" then
		BH.Options:Open()
	end
end

MiniMapIcon:SetScript("OnMouseUp", MiniMapIconOnClick)

BH.Options.MiniMapDropdown = CreateFrame("Frame", "BHMiniMapMenuFrame", nil, "UIDropDownMenuTemplate")

local MinimapMenu_UIDs = {}
local MinimapMenu_UIDnumeric = 0
local MinimapMenu_Level = {3,4,5,5}

function BH.F.MinimapMenuAdd(text, func, level, uid, subMenu)
	level = level or 2
	if not uid then
		MinimapMenu_UIDnumeric = MinimapMenu_UIDnumeric + 1
		uid = MinimapMenu_UIDnumeric
	end
	if MinimapMenu_UIDs[uid] then
		return
	end
	local menuTable = { text = text, func = func, notCheckable = true, keepShownOnClick = true, }
	if subMenu then
		menuTable.hasArrow = true
		menuTable.menuList = subMenu
	end
	tinsert(BH.F.menuTable,MinimapMenu_Level[level],menuTable)
	for i=level,#MinimapMenu_Level do
		MinimapMenu_Level[i] = MinimapMenu_Level[i] + 1
	end
	MinimapMenu_UIDs[uid] = menuTable
end

function BH.F.MinimapMenuRemove(uid)
	for i=1,#BH.F.menuTable do
		if BH.F.menuTable[i] == MinimapMenu_UIDs[uid] then 
			for j=i,#BH.F.menuTable do
				BH.F.menuTable[j] = BH.F.menuTable[j+1]
			end
			for j=1,#MinimapMenu_Level do
				if i <= MinimapMenu_Level[j] then
					MinimapMenu_Level[j] = MinimapMenu_Level[j] - 1
				end
			end
			MinimapMenu_UIDs[uid] = nil
			return
		end
	end
end

function BH.Options:Open(PANEL)
	CloseDropDownMenus()
	Options:Show()
	
	if Options.CurrentFrame then
		Options.CurrentFrame:Hide()
	end
	Options.CurrentFrame = PANEL or Options.Frames[Options.modulesList.selected or 1]
	Options.CurrentFrame:Show()
	
	if PANEL then
		for i=1,#Options.Frames do
			if Options.Frames[i] == PANEL then
				Options.modulesList.selected = i
				Options.modulesList:Update()
				break
			end
		end
	end
end

BH.F.menuTable = {
{ text = L.minimapmenu, isTitle = true, notCheckable = true, notClickable = true },
{ text = L.minimapmenuset, func = BH.Options.Open, notCheckable = true, keepShownOnClick = true, },
{ text = " ", isTitle = true, notCheckable = true, notClickable = true },
{ text = " ", isTitle = true, notCheckable = true, notClickable = true },
{ text = L.minimapmenuclose, func = function() CloseDropDownMenus() end, notCheckable = true },
}

local modulesActive = {}
function BH.Options:UpdateModulesList()
	for i=1,#BH.ModulesOptions do
		BH.F.MinimapMenuAdd(BH.ModulesOptions[i].name, function() 
			BH.Options:Open(BH.ModulesOptions[i]) 
		end, 2,BH.ModulesOptions[i].name)
	end
end

----> Options

-->OptionsFrame.image = BHLib:Texture(OptionsFrame,"Interface\\AddOns\\BH\\media\\OptionLogo2"):Point("CENTER",OptionsFrame,"TOPLEFT",75,-60):Size(140,140):Color(.9,.9,.9,1):TexCoord(0,140/256,0,140/256)
OptionsFrame.title = BHLib:Text(OptionsFrame,"BETA Heal",22):Size(500,22):Point("CENTER",OptionsFrame,"TOPRIGHT",75,-60):Color()

OptionsFrame.chkIconMiniMap = BHLib:Check(OptionsFrame,L.setminimap1,"",0):Point(25,-150):OnClick(function(self) 
	if self:GetChecked() then
		VBH.Addon.IconMiniMapHide = true
		BH.MiniMapIcon:Hide()
	else
		VBH.Addon.IconMiniMapHide = nil
		BH.MiniMapIcon:Show()
	end
end)
OptionsFrame.chkIconMiniMap:SetScript("OnShow", function(self,event) 
	self:SetChecked(VBH.Addon.IconMiniMapHide) 
end)

OptionsFrame.authorLeft = BHLib:Text(OptionsFrame,L.setauthor,12):Size(150,25):Point(15,-195):Shadow():Top()
OptionsFrame.authorRight = BHLib:Text(OptionsFrame,"Sheldøne",12):Size(520,25):Point(135,-195):Color():Shadow():Top()

OptionsFrame.versionLeft = BHLib:Text(OptionsFrame,L.setver,12):Size(150,25):Point(15,-215):Shadow():Top()
OptionsFrame.versionRight = BHLib:Text(OptionsFrame,BH.V..(BH.T == "R" and "" or " "..BH.T),12):Size(520,25):Point(135,-215):Color():Shadow():Top()

OptionsFrame.contactLeft = BHLib:Text(OptionsFrame,L.setcontact,12):Size(150,25):Point(15,-235):Shadow():Top()
OptionsFrame.contactRight = BHLib:Text(OptionsFrame,"sur discord ou IG",12):Size(520,25):Point(135,-235):Color():Shadow():Top()


if L.TranslateBy ~= "" then
	OptionsFrame.translateLeft = BHLib:Text(OptionsFrame,L.SetTranslate,12):Size(150,25):Point("LEFT",OptionsFrame,15,0):Point("TOP",OptionsFrame.thanksRight,"BOTTOM",0,-8):Shadow():Top()
	OptionsFrame.translateRight = BHLib:Text(OptionsFrame,L.TranslateBy,12):Size(520,25):Point("LEFT",OptionsFrame.thanksRight,"LEFT",0,0):Point("TOP",OptionsFrame.translateLeft,0,0):Color():Shadow():Top()
end

OptionsFrame.Changelog = BHLib:ScrollFrame(OptionsFrame):Size(620,160):Point(15,-325):OnShow(function(self) -- fennetre changelog
	local isFind
	local text = (BH.Options.Changelog or ""):gsub("^[ \t\n]*","|cff99ff99"):gsub("v%.(%d+)",function(ver)
		if not isFind and ver ~= tostring(BH.V) then
			isFind = true
			return "|rv."..ver
		end
	end)
	self.Text:SetText(text)
	--self.Text:SetTextColor(1,0,0,1)
	self:Height(self.Text:GetStringHeight()+30)
	self:OnShow()
end,true)
--OptionsFrame.Changelog.backdrop:SetBackdropColor(1,0,0,1)
OptionsFrame.Changelog.Text = BHLib:Text(OptionsFrame.Changelog.C,"",12):Point("TOPLEFT",5,0):Point("TOPRIGHT",-5,0):Left():Color(1,1,1)
OptionsFrame.Changelog.Header = BHLib:Text(OptionsFrame.Changelog,"Changelog",12):Point("BOTTOMLEFT",OptionsFrame.Changelog,"TOPLEFT",0,4):Left()

local VersionCheckReqSended = {}
local function UpdateVersionCheck()
	OptionsFrame.VersionUpdateButton:Enable()
	local list = OptionsFrame.VersionCheck.L
	wipe(list)
	
	if IsInRaid() then
		for i=1,GetNumGroupMembers() do
			local name,_,_,_,_,class = GetRaidRosterInfo(i)
			if name then
				list[#list + 1] = {
					"|c"..BH.F.classColor(class or "?")..name,
					0,
					name,
				}
			end
		end
	else
		for _,unit in pairs({"party1","party2","party3","party4","player"}) do
			local name,realm = UnitName(unit)
			if name then
				if realm and realm ~= "" then
					name = name .. "-" .. realm
				end
				local _,class = UnitClass(unit)
				
				list[#list + 1] = {
					"|c"..BH.F.classColor(class or "?")..name,
					0,
					name,
				}
			end
		end
	end
	
	for i=1,#list do
		local name = list[i][3]
		local ver = BH.RaidVersions[name]
		if not ver and not name:find("%-") then
			for long_name,v in pairs(BH.RaidVersions) do
				if long_name:find("^"..name) then
					ver = v
					break
				end
			end
		end
		if not ver then
			if VersionCheckReqSended[name] then
				ver = "|cffff8888no addon"
			else
				ver = "???"
			end
		elseif not tonumber(ver) then
			ver = "|cffff8888"..ver
		elseif tonumber(ver) >= BH.V then
			ver = "|cff88ff88"..ver
		else
			ver = "|cffffff88"..ver
		end
		
		list[i][2] = ver
	end
	
	sort(list,function(a,b) return a[3]<b[3] end)
	--[[for i=1,#list do --debug de la liste afficher pour le reset version
	   for j=1,#list[i] do
			print(list[i][j])
		  end
	end]]
	OptionsFrame.VersionCheck:Update()
	
end

OptionsFrame.VersionCheck = BHLib:ScrollTableList(OptionsFrame,0,130):Point("TOPLEFT",15,-501):Size(350,110)
OptionsFrame.VersionUpdateButton = BHLib:Button(OptionsFrame,UPDATE):Point("TOPLEFT",OptionsFrame.VersionCheck,"TOPRIGHT",10,0):Size(100,20):OnClick(function()
	BH.F.SendExMsg("needversion","")
	C_Timer.After(2,UpdateVersionCheck)
	if IsInRaid() then
		for i=1,GetNumGroupMembers() do
			local name = GetRaidRosterInfo(i)
			if name then
				VersionCheckReqSended[name]=true
			end
		end
	else
		for _,unit in pairs({"player","party1","party2","party3","party4"}) do
			local name,realm = UnitName(unit)
			if name then
				if realm and realm ~= "" then
					name = name .. "-" .. realm
				end
				VersionCheckReqSended[name]=true
			end
		end
	end	
	local list = OptionsFrame.VersionCheck.L
	for i=1,#list do
		list[i][2] = "..."
	end
	OptionsFrame.VersionCheck:Update()
	OptionsFrame.VersionUpdateButton:Disable()
end)

OptionsFrame.VersionCheck:SetScript("OnShow",UpdateVersionCheck)

local function CreateDataBrokerPlugin()
	local dataObject = LibStub:GetLibrary('LibDataBroker-1.1'):NewDataObject(GlobalAddonName, {
		type = 'launcher',
		icon = "Interface\\AddOns\\BH\\libs\\media\\MiniMap",
		OnClick = MiniMapIconOnClick,
	})
end
CreateDataBrokerPlugin()