local addonName, TC = ...
TC.Broadcaster = {}

TC.Broadcaster.timeRemaining = 0 
local ticker = nil

function TC.Broadcaster:Initialize()
    local interval = TC.db.profile.interval or 15
    self.timeRemaining = interval * 60
    self:StartTicker()
end

function TC.Broadcaster:StartTicker()
    if ticker then ticker:Cancel() end
    ticker = C_Timer.NewTicker(1, function()
        if not TC.db.profile.enabled then 
            if TC.UI and TC.UI.timerText then TC.UI.timerText:SetText("|cFFFF0000PAUSED|r") end
            return 
        end

        self.timeRemaining = self.timeRemaining - 1

        if TC.UI and TC.UI.timerText then
            local m = math.floor(self.timeRemaining / 60)
            local s = self.timeRemaining % 60
            TC.UI.timerText:SetText(string.format("%02d:%02d", m, s))
            if self.timeRemaining < 60 then
                TC.UI.timerText:SetTextColor(1, 0.2, 0.2)
            else
                TC.UI.timerText:SetTextColor(1, 0.82, 0)
            end
        end

        if self.timeRemaining <= 0 then
            self:Execute()
        end
    end)
end

function TC.Broadcaster:BroadcastFunFact()
    if not TC.Data or not TC.Data.FunFacts then return end
    local fact = TC.Data.FunFacts[math.random(1, #TC.Data.FunFacts)]
    self:QueueOrSend(fact)
end

function TC.Broadcaster:Execute()
    local finalMsg = ""
    local messages = TC.db.profile.messages or {}
    
    if TC.db.profile.autoFunFacts and (math.random() > 0.5) then
        finalMsg = "Fun Fact: " .. TC.Data.FunFacts[math.random(1, #TC.Data.FunFacts)]
    elseif #messages > 0 then
        local msg = table.remove(messages, 1)
        table.insert(messages, msg)
        finalMsg = msg
    end

    if finalMsg ~= "" then
        self:QueueOrSend(finalMsg)
    end
    self.timeRemaining = (TC.db.profile.interval or 15) * 60
end

function TC.Broadcaster:QueueOrSend(msg)
    if InCombatLockdown() then
        local f = CreateFrame("Frame")
        f:RegisterEvent("PLAYER_REGEN_ENABLED")
        f:SetScript("OnEvent", function(s)
            self:SendMessage(msg)
            s:UnregisterAllEvents()
        end)
    else
        self:SendMessage(msg)
    end
end

function TC.Broadcaster:SendMessage(msg)
    local chan = TC.db.profile.channel or "GUILD"
    SendChatMessage("TownCrier: " .. msg, chan)
    if TC.LogToLedger then TC:LogToLedger("|cFF00FFFF[Broadcaster]|r " .. msg) end
end

function TC.Broadcaster:UpdateInterval(newMinutes)
    self.timeRemaining = newMinutes * 60
end