local addonName, addon = ...



--[[-----------------------------------------------------------------------------
GrimUI options/config button
-------------------------------------------------------------------------------]]
local configButton = CreateFrame('Button', configButton, UIParent, 'SecureHandlerClickTemplate')

configButton:SetHeight(30)
configButton:SetWidth(62)
configButton:RegisterForClicks('AnyUp')
configButton:SetNormalTexture([[Interface\AddOns\]] .. addonName .. [[\Media\ConfigButton]])
configButton:SetHighlightTexture([[Interface\AddOns\]] .. addonName .. [[\Media\ConfigButton]])
configButton:SetPoint('BOTTOMRIGHT', addon.skin, 'TOPRIGHT', -2, 0)
	
configButton:SetAttribute('_onclick', [[
	if button == 'LeftButton' and not IsControlKeyDown() then
		local microBar = self:GetFrameRef("microBar")
		if microBar:IsVisible() then
			microBar:Hide()
		else
			microBar:Show()
		end
	elseif button == 'RightButton' and not IsControlKeyDown() then
		control:CallMethod("OpenConfig")
	end
	
]])


function configButton:OpenConfig()
	if addon.configPanel then 
		if addon.configPanel:IsVisible() then
			InterfaceOptionsFrame:Hide()
		else
			addon.configPanel()
		end
	end
end

configButton:SetScript('OnEnter', function(self)
	GameTooltip:SetOwner(self, 'ANCHOR_TOP', 0, 15)
	GameTooltip:AddLine("|cffeda55fLeftClick|r toggle MicroBar", 0.2, 1, 0.2)
	GameTooltip:AddLine("|cffeda55fRightClick|r Options Panel", 0.2, 1, 0.2)
	if Macaroon then 
		GameTooltip:AddLine("|cffeda55fCtrl+LeftClick|r Button Binds", 0.2, 1, 0.2)
		GameTooltip:AddLine("|cffeda55fCtrl+RightClick|r Button Config", 0.2, 1, 0.2)
end
	GameTooltip:Show()
end)

configButton:HookScript("OnClick", function(self, button)
	if Macaroon then
		if button == 'LeftButton' and IsControlKeyDown() then
			Macaroon.ButtonBind(off)
		elseif IsControlKeyDown() and button == 'RightButton' then
			Macaroon.ConfigBars()
		end
	end
end)

		

configButton:SetScript('OnLeave', addon.HideTooltip)

--[[-----------------------------------------------------------------------------
Bag bar
-------------------------------------------------------------------------------]]
local bagBar = CreateFrame('Frame', nil, UIParent, 'SecureActionButtonTemplate')
bagBar:SetPoint('BOTTOMRIGHT', configButton, 'TOPRIGHT', -3, 1)
bagBar:SetHeight(1)
bagBar:SetWidth(1)

addon.backpackButton:SetFrameRef("bagBar", bagBar)

local anchor = bagBar
for _, frame in ipairs({ MainMenuBarBackpackButton, CharacterBag0Slot, CharacterBag1Slot, CharacterBag2Slot, CharacterBag3Slot }) do
	frame:ClearAllPoints()
	frame:SetPoint('BOTTOMRIGHT', anchor, 'TOPRIGHT', 0, 2)
	frame:SetParent(bagBar)
	addon:LockFrame(frame)
	anchor = frame
end
MainMenuBarBackpackButton:SetScale(37/37)

--[[-----------------------------------------------------------------------------
Micro buttons bar
-------------------------------------------------------------------------------]]
local microBar = CreateFrame('Frame', nil, UIParent, 'SecureActionButtonTemplate')
microBar:SetPoint('BOTTOMRIGHT', configButton, 'BOTTOMLEFT', -1, 0)
microBar:SetHeight(1)
microBar:SetWidth(1)
microBar:SetScale(33/37)


local buttons = { CharacterMicroButton, SpellbookMicroButton, TalentMicroButton, AchievementMicroButton, PVPMicroButton, LFDMicroButton, RaidMicroButton, EJMicroButton, MainMenuMicroButton, HelpMicroButton }
-- removed FriendsMicroButton, QuestLogMicroButton, GuildMicroButton,  - return to above list to have them appear in the MicroBar again.

local anchorFrame, anchorPoint = microBar, 'BOTTOMRIGHT'
for index = #buttons, 1, -1 do
	local button = buttons[index]
	button:SetParent(microBar)
	button.SetParent = addon.DoNothing
	button:ClearAllPoints()
	button:SetPoint('BOTTOMRIGHT', anchorFrame, anchorPoint, 1, 0)
	addon:LockFrame(button)
	anchorFrame, anchorPoint = button, 'BOTTOMLEFT'
end
microBar:SetWidth(buttons[#buttons]:GetRight() - buttons[1]:GetLeft() + 1)
microBar:SetHeight(buttons[1]:GetHeight())

configButton:SetFrameRef("microBar", microBar)

-- added insurance they stay hidden
addon:HideFrame("FriendsMicroButton")
addon:HideFrame("QuestLogMicroButton")
addon:HideFrame("GuildMicroButton")




--[[-----------------------------------------------------------------------------
Initialize
-------------------------------------------------------------------------------]]
addon.RegisterEvent("Features-Initialize", 'PLAYER_ENTERING_WORLD', function(self, event)
	addon.UnregisterEvent(self, event)

	if not addon.settings.showBagBar then
		bagBar:Hide()
	end
	if not addon.settings.showMicroBar then
		microBar:Hide()
	end
	addon:InitWatchFrame()
	
end)

function addon:InitWatchFrame()
	if addon.settings.showWatchFrame == true then
		addon:ShowFrame(WatchFrame)
	else
		addon:HideFrame(WatchFrame)
	end
end

--[[-----------------------------------------------------------------------------
Save settings on logout
-------------------------------------------------------------------------------]]
addon.RegisterEvent("Features-SaveState", 'PLAYER_LOGOUT', function()
	addon.settings.showBagBar = bagBar:IsShown() or false
	addon.settings.showMicroBar = microBar:IsShown() or false
	if WatchFrame:IsShown() then
		addon.settings.showWatchFrame = true
	else
		addon.settings.showWatchFrame = false
	end
end)

--[[-----------------------------------------------------------------------------
Auto loot hot point
-------------------------------------------------------------------------------]]
local lootHotPoint = CreateFrame('Button', nil, UIParent)
lootHotPoint:SetPoint('TOPRIGHT', addon.skin[1], 'TOPRIGHT', -86, -2)
lootHotPoint:SetHeight(16)
lootHotPoint:SetWidth(16)
lootHotPoint:RegisterForClicks('LeftButtonUp', 'RightButtonUp')

local HotBG = lootHotPoint:CreateTexture(nil, "BACKGROUND")
HotBG:SetTexture("Interface\\AddOns\\GrimUI\\Media\\HotSpotGlow")
HotBG:SetPoint('CENTER', lootHotPoint, 'CENTER')
HotBG:SetHeight(43)
HotBG:SetWidth(43)
HotBG:Hide()

lootHotPoint:SetScript('OnClick', function(self, button)
	if button == 'LeftButton' and not IsControlKeyDown() then
		if GetCVarBool('autoLootDefault') then
			SetCVar('autoLootDefault', "0")
			UIErrorsFrame:AddMessage("AutoLoot Off", 1.0, 0.0, 0.0, 53, 3);
		else
			SetCVar('autoLootDefault', "1")
			UIErrorsFrame:AddMessage("AutoLoot On", 0.0, 1.0, 0.0, 53, 3);
		end
	elseif IsControlKeyDown() and button == 'LeftButton' then
		if WatchFrame:IsShown() then
			addon:HideFrame(WatchFrame)
			addon.settings.showWatchFrame = false
		else
			addon:ShowFrame(WatchFrame)
			addon.settings.showWatchFrame = true
		end
	else
		SlashCmdList.RANDOM(100)
	end
end)

lootHotPoint:SetScript('OnEnter', function(self)
	GameTooltip:SetOwner(self, 'ANCHOR_TOP', 0, 10)
	GameTooltip:AddLine("|cffeda55fLeftClick|r toggle AutoLoot", 0.2, 1, 0.2)
	GameTooltip:AddLine("|cffeda55fRightClick|r to /roll", 0.2, 1, 0.2)
	GameTooltip:AddLine("|cffeda55fCtrl+LeftClick|r to toggle Objectives", 0.2, 1, 0.2)
	GameTooltip:Show()
	HotBG:Show()
end)

lootHotPoint:SetScript('OnLeave', function(self)
	GameTooltip:Hide()
	HotBG:Hide()
end)

--[[-----------------------------------------------------------------------------
Friends list class coloring 
-------------------------------------------------------------------------------]]

hooksecurefunc('FriendsList_Update', function()
	local buttons, button = FriendsFrameFriendsScrollFrame.buttons
	local colors, CLASS = CUSTOM_CLASS_COLORS or RAID_CLASS_COLORS, addon.CLASS
	for index = 1, #buttons do
		button = buttons[index]
		if button:IsShown() then
			if button.buttonType == FRIENDS_BUTTON_TYPE_WOW then
				local _, _, class, _, connected = GetFriendInfo(button.id)
				if connected then
					local color = colors[CLASS[class]]
					button.name:SetTextColor(color.r, color.g, color.b)
				end
			end
		else
			break
		end
	end
end)


--[[-----------------------------------------------------------------------------
Quest log expand/collapse all buttons
-------------------------------------------------------------------------------]]
local function CreateMiniButton(...)
	local button = CreateFrame('Button', nil, QuestLogFrame)
	button:SetHeight(22)
	button:SetWidth(22)
	button:SetPoint(...)
	button:RegisterForClicks('AnyUp')
	button:SetHighlightTexture([[Interface\Buttons\UI-PlusButton-Hilight]])
	return button
end

local collapseAll = CreateMiniButton('LEFT', QuestLogCount, 'RIGHT', 15, 0)
collapseAll:SetNormalTexture([[Interface\Buttons\UI-MinusButton-Up]])
collapseAll:SetPushedTexture([[Interface\Buttons\UI-MinusButton-Down]])		
collapseAll:SetScript('OnClick', function()
	CollapseQuestHeader(0)
end)

local expandAll = CreateMiniButton('LEFT', collapseAll, 'RIGHT', 3, 0)
expandAll:SetNormalTexture([[Interface\Buttons\UI-PlusButton-Up]])
expandAll:SetPushedTexture([[Interface\Buttons\UI-PlusButton-Down]])
expandAll:SetScript('OnClick', function()
	ExpandQuestHeader(0)
end)

--[[-----------------------------------------------------------------------------
PVP Battleground
-------------------------------------------------------------------------------]]
if PVPBattlegroundFrame then
	if PVPBattlegroundFrameFrameLabel then		-- Display fix for 3.1+
		PVPBattlegroundFrameFrameLabel:ClearAllPoints()
		PVPBattlegroundFrameFrameLabel:SetPoint('TOP', PVPBattlegroundFrame, 'TOP', 0, -17)
	end
	if PVPBattlegroundFrameNameHeader then		-- Display fix for 3.2+
		PVPBattlegroundFrameNameHeader:ClearAllPoints()
		PVPBattlegroundFrameNameHeader:SetPoint('TOPLEFT', PVPBattlegroundFrame, 'TOPLEFT', 70, -55)
	end
end

--[[-----------------------------------------------------------------------------
Sell all grey items
-------------------------------------------------------------------------------]]
local sellGreys = CreateFrame('Button', nil, MerchantFrame, 'OptionsButtonTemplate')
sellGreys:SetPoint('TOPRIGHT', MerchantFrameCloseButton, 'BOTTOMRIGHT', -8, 4)
sellGreys:SetText("Sell Greys")
sellGreys:RegisterForClicks('AnyUp')
sellGreys:SetScript('OnClick', function()
	local total = 0
	for bag = 0, NUM_BAG_FRAMES do
		for slot = 1, GetContainerNumSlots(bag) do
			local link = GetContainerItemLink(bag, slot)
			if link then
				local _, _, itemRarity, _, _, _, _, _, _, _, itemSellPrice = GetItemInfo(link)
				local _, itemCount = GetContainerItemInfo(bag, slot)
				if itemRarity == 0 and itemSellPrice ~= 0 then
					total = total + (itemSellPrice * itemCount)
					UseContainerItem(bag, slot)
				end
			end
		end
	end
	if total ~= 0 then
		print("|cff33ff99" .. addonName .. "|r: Sold all grey items for " .. addon:MoneyToString(total))
	end
end)

--[[-----------------------------------------------------------------------------
Item border coloring for CharacterFrame and InspectFrame
-------------------------------------------------------------------------------]]
local borders, slots = { }, addon.itemSlots

local qualityColor = setmetatable({ }, { __index = function(self, key)
	local red, green, blue = key:match("(%x%x)(%x%x)(%x%x)")
	self[key] = { tonumber(red, 16) / 255, tonumber(green, 16) / 255, tonumber(blue, 16) / 255 }
	return self[key]
end })

local function UpdateItemQualityBorders(frame, _, unit)
	if frame.unit ~= unit then return end
	local border = borders[frame]
	for id = 1, #slots do
	local link = GetInventoryItemLink(unit, id)                                         -- GetInventoryItemQuality doesn't work for InspectFrame
	if link then
	local color = qualityColor[link:match("|[Cc][Ff][Ff](%x%x%x%x%x%x)")]
	border[id]:SetVertexColor(color[1], color[2], color[3])
	border[id]:Show()
	else
	border[id]:Hide()
	end

	end

end

local function GetNormalTexture(...)-- The normal textures for InspectFrame's buttons aren't named...
	for index = 1, select('#', ...) do
		local region = select(index, ...)
		if region.GetTexture and region:GetTexture() == [[Interface\Buttons\UI-Quickslot2]] then
			return region
		end
	end
end

local function CreateBorders(frame, prefix)
	local border = { }
	for id = 1, #slots do
	local frame = _G[prefix .. slots[id]]
	local region = GetNormalTexture(frame:GetRegions())
	local texture = frame:CreateTexture(nil, 'OVERLAY')
	texture:SetTexture([[Interface\Buttons\UI-ActionButton-Border]])
	texture:SetBlendMode('ADD')
	texture:SetAlpha(0.8)
	texture:SetPoint('TOPLEFT', region, -1, 3)
	texture:SetPoint('BOTTOMRIGHT', region, 1, 0)
	border[id] = texture
	end
	borders[frame] = border
end

local function OnHide(self)
	addon.UnregisterEvent(self, 'UNIT_INVENTORY_CHANGED')
end

local function OnShow(self)
	addon.RegisterEvent(self, 'UNIT_INVENTORY_CHANGED', UpdateItemQualityBorders)
	UpdateItemQualityBorders(self, nil, self.unit)
end

local function HookFrame(frame, prefix)
	CreateBorders(frame, prefix)
	frame:HookScript('OnHide', OnHide)
	frame:HookScript('OnShow', OnShow)
end

HookFrame(CharacterFrame, 'Character')
CharacterFrame.unit = 'player'


addon.RegisterEvent("Features-MonitorInspectUI", 'ADDON_LOADED', function(self, event, name)
	if name ~= 'Blizzard_InspectUI' then return end
	addon.UnregisterEvent(self, event)

	HookFrame(InspectFrame, 'Inspect')
	InspectFrame.unit = 'target'
	
end)


