--[[
Author: Jarth
Filename: CBs_Bindings.lua
]] --
-------------------------------------------------------------------------------------------------
-- VARIABLES --
-------------------------------------------------------------------------------------------------
local base = CollectionBars
local texts = base.Texts

-------------------------------------------------------------------------------------------------
-- FUNCTIONS --
-------------------------------------------------------------------------------------------------
function CBs_ShowSettings()
	base:ToggleEnableSettings(base.ShowSettings())
end

function CBs_Clicked(keyId)
	base:Debug("CBs_Clicked", keyId)

	local control = base.WM:GetMouseOverControl()
	local collectibleId = base.Saved.Bindings[keyId]

	if control ~= nil and control.CBs then
		local newCId = control:GetId()
		local previousCId = collectibleId

		if previousCId ~= newCId then
			for _keyId, cid in ipairs(base.Saved.Bindings) do
				if _keyId ~= keyId and cid == newCId then
					base.Saved.Bindings[_keyId] = 0
				end
			end

			for cid, _keyId in pairs(base.Global.ReverseBindings) do
				if cid ~= newCId and _keyId == keyId then
					base.Global.ReverseBindings[cid] = nil
					base:SetBindingText(cid)
				end
			end

			base.Saved.Bindings[keyId] = newCId
			base.Global.ReverseBindings[newCId] = keyId
			base:SetBindingText(newCId)
		end
	elseif collectibleId > 0 then
		if base.AllButtons[collectibleId] then
			base:Activate(base.AllButtons[collectibleId])
		else
			UseCollectible(collectibleId)
		end
	end
end

function base:SetBindingText(cid)
	base:Debug("SetBindingText", cid)

	if base.AllButtons[cid] then
		base.AllButtons[cid]:SetBindingText(base.Saved.Bindings.Show, cid)
	end
end

function base:InitializeBindings()
	base:Debug("InitializeBindings")

	ZO_CreateStringId(string.format(texts.FormatBindingName, "Settings"), "Settings")

	for key, _ in ipairs(base.Saved.Bindings) do
		ZO_CreateStringId(string.format(texts.FormatBindingName, key), string.format(texts.FormatAbbreviationLowDash, key))
	end
end

function base:InitializeReverseBinding()
	base:Debug("InitializeReverseBinding")

	for keyId, collectibleId in ipairs(base.Saved.Bindings) do
		if collectibleId > 0 then
			base.Global.ReverseBindings[collectibleId] = keyId
		end
	end
end