local M = _G["MecDrumsAlarm"]
local API = M.API

local function HandleCombatEvent(_, event, ...)
    local _, subevent, _, sourceName, _, _, destName, _, _, spellName = ...

    -- Track who last applied drums to the player to avoid announcing other players' drums.
    if subevent == "SPELL_AURA_APPLIED" or subevent == "SPELL_AURA_REFRESH" then
        if destName ~= M.Player.Name then return end
        if spellName ~= M.Config.drumType then return end
        if not API:IsInRaid() then return end

        M.Player.lastDrumAppliedBy = sourceName
        return
    end

    -- Handle when drums are used.
    if subevent == "SPELL_CAST_SUCCESS" then
        local unitName = sourceName
        local drumName = spellName

        if drumName ~= M.Config.drumType then return end
        if not API:IsUnitInParty(unitName) then return end
        if not API:IsInRaid() then return end

        M.Rotation.timeOfMostRecentDrumming = GetTime()
        M.Raiders.data[unitName].cooldown = 120
        M.Raiders.data[unitName].eligibilityStatus = "Drummed"
        M.DetectPulls.pullActive = true
        M.GUI.MasterFrame:Render()
        M.Rotation.isInFlagToDrumGracePeriod = true

        -- If this was our own drum cast, optionally announce to party.
        if unitName == M.Player.Name and M.Config.drumStartMessage and M.Config.drumStartMessage ~= "" then
            M.Player.lastDrumAppliedBy = M.Player.Name
            SendChatMessage(M.Config.drumStartMessage, "PARTY")
        end
        return
    end

    -- Handle when our own drum buff ends.
    if subevent == "SPELL_AURA_REMOVED" then
        if destName ~= M.Player.Name then return end
        if spellName ~= M.Config.drumType then return end
        if not API:IsInRaid() then return end

        if M.Player.lastDrumAppliedBy ~= M.Player.Name then return end
        if M.Config.drumEndMessage and M.Config.drumEndMessage ~= "" then
            SendChatMessage(M.Config.drumEndMessage, "PARTY")
        end
    end
end

local frame = CreateFrame("Frame")
frame:RegisterEvent("COMBAT_LOG_EVENT_UNFILTERED")
frame:SetScript("OnEvent", HandleCombatEvent)
