--[[---------------------------------------------------------------------------

  Grichelde - Text Replacer
  Copyright 2020 Teilzeit-Jedi <tj@teilzeit-jedi.de>

  This addon is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  GNU General Public License for more details.

  You should have received a copy of the GNU General Public License
  along with the addon. If not, see <http://www.gnu.org/licenses/gpl-3.0.txt>.

-----------------------------------------------------------------------------]]

-- read namespace from global env
local AddonName, AddonTable = ...
local _G = _G

-- initialize addon
local Grichelde = LibStub("AceAddon-3.0"):NewAddon(AddonTable, AddonName, "AceConsole-3.0", "AceEvent-3.0", "AceHook-3.0")
Grichelde.L = LibStub("AceLocale-3.0"):GetLocale("Grichelde", true)
Grichelde.version = GetAddOnMetadata(AddonName, "Version")
Grichelde.build = GetAddOnMetadata(AddonName, "X-Build") or "Experimental"
Grichelde.classic = _G.WOW_PROJECT_ID == _G.WOW_PROJECT_CLASSIC
Grichelde.logLevel = 0      -- cannot reference Grichelde.LOG_LEVELs here as they are loaded afterwards

-- publish to global env
_G.Grichelde = Grichelde

-- Ace3 callbacks
function Grichelde:OnInitialize()
    -- Build Interface Options window
    self.db = self:LoadDatabase()
    self:UpgradeDatabase()

    self.options, self.dialog = self:SetupOptions()
    self:RefreshOptions("OnProfileChanged")

    self.ldb, self.icon = self:MinimapButton()

    self:SetupSlashCommands()
end

function Grichelde:OnEnable()
    -- Hook in before message is sent to replace all character occurrences where replacements have been defined in the options
    self:RawHook("SendChatMessage", true)

    -- tell the world we are listening
    self:Print(self.L.AddonLoaded, self.COLOR_CODES.PREFIX .. self.L.AddonName .. " " .. self.L.VersionAbbr .. self.version .. self.COLOR_CODES.CLOSE)
end

function Grichelde:OnDisable()
    self:Unhook("SendChatMessage")
end

--- Register  slash commands 'gri' and 'grichelde'
function Grichelde:SetupSlashCommands()
    self:RegisterChatCommand("grichelde", "HandleSlashCommand")
    self:RegisterChatCommand("gri", "HandleSlashCommand")
end

function Grichelde:HandleSlashCommand(input)
    -- Show the GUI if no input is supplied, otherwise handle the chat input.
    if self.functions.nilOrEmpty(input) then
        self:OpenOptions()
    else
        -- handle slash ourselves
        self:DebugPrint("Handle slash command: " .. input)
        if input == "mappings" then
            self:ToogleMappings()
        elseif input == "options" then
            self:PrintOptions()
        elseif input == "profile" then
            self:PrintProfile()
        end
    end
end