local _, DX = ...

local LSM = LibStub("LibSharedMedia-3.0")

local moduleName = "MovementTracker"
local moduleDesc = "Tracks different movement cooldowns like Blink, Shimmer or Shift"
local moduleTicker

local movementCooldowns = {
    Blink = 1953,
    Shimmer = 212653,
    Shift = 123
}

local movementConfig = {
    [movementCooldowns.Blink] = {
        text = "No Blink: "
    },
    [movementCooldowns.Shimmer] = {
        text = "No Shimmer: "
    },
    [movementCooldowns.Shift] = {
        text = "No Shift: "
    }
}

local function LoadMovementTracker()
    local eventFrame = CreateFrame("Frame")

    -- Create the frame
    local trackerFrame = CreateFrame("Frame", "DX_MovementTracker", UIParent)
    trackerFrame:SetSize(400, 50)
    trackerFrame:SetPoint("CENTER", UIParent, "CENTER", 0, 18)
    trackerFrame:SetFrameStrata("LOW")
    trackerFrame:Show()

    local trackerText = trackerFrame:CreateFontString(nil, "OVERLAY")
    local trackerFont = LSM:Fetch("font", "DX Narrow")
    trackerText:SetFont(trackerFont, 20, "OUTLINE")
    trackerText:SetPoint("CENTER")
    trackerText:SetJustifyH("CENTER")
    trackerText:SetTextColor(1, 1, 1, 1)

    -- Returns the spellId of the learned movement cooldown
    local function getRelevantSpellId()
        if C_SpellBook.IsSpellKnown(movementCooldowns.Shimmer) then
            return movementCooldowns.Shimmer
        elseif C_SpellBook.IsSpellKnown(movementCooldowns.Blink) then
            return movementCooldowns.Blink
        elseif C_SpellBook.IsSpellKnown(movementCooldowns.Shift) then
            return movementCooldowns.Shift
        else
            -- No spell known
            return -1
        end
    end

    -- Applies the cooldown to the TextFrame and hide/shows it accordingly
    local function applyCooldownText()
        local spellId = getRelevantSpellId()
        local config = movementConfig[spellId]
        local durationObject = C_Spell.GetSpellCooldownDuration(spellId)
        local cooldown =  durationObject:GetRemainingDuration(1)

        -- Ignore spell if only on GCD or not on cooldown
        if (C_Spell.GetSpellCooldown(spellId).isOnGCD ~= false) or (not cooldown) or (cooldown == 0) then
            trackerFrame:Hide()
            if moduleTicker then
                moduleTicker:Cancel()
            end
            return
        end

        trackerFrame:Show()
        trackerText:SetText(string.format("%s%.1f", config.text, cooldown))
    end

    function eventFrame:SPELL_UPDATE_COOLDOWN()
        if getRelevantSpellId() == -1 then
            return
        end
        if moduleTicker then
            moduleTicker:Cancel()
        end
        moduleTicker = C_Timer.NewTicker(0.1, applyCooldownText)
    end

    eventFrame:SetScript("OnEvent", function(self, event, ...) return self[event](self, ...) end)
    eventFrame:RegisterEvent("SPELL_UPDATE_COOLDOWN")
end

DX:AddModule(moduleName, moduleDesc, LoadMovementTracker)