--[[
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)
    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 pairs(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.Buttons[collectibleId] then
            base.Activate(base.Buttons[collectibleId])
        else
            UseCollectible(collectibleId)
        end
    end
end

function base.SetbindingText(cid) if base.Buttons[cid] then base.Buttons[cid]:SetBindingText(base.Saved.ShowBinding, cid) end end

function base.InitializeBindings()
    local bindingsName = texts.Components.SIBindingName .. base.Addon.Abbreviation .. texts.Helpers.Lowdash
    ZO_CreateStringId(bindingsName .. texts.Components.Settings, texts.Components.Settings)
    for key, _ in ipairs(base.Saved.Bindings) do ZO_CreateStringId(bindingsName .. key, base.Addon.Abbreviation .. texts.Helpers.Lowdash .. key) end
end

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