local _, PUP = ... -- Internal namespace
local f = CreateFrame("Frame")
f:RegisterEvent("ENCOUNTER_START")
f:RegisterEvent("PLAYER_LOGIN")

f:SetScript("OnEvent", function(self, e, ...)
    PUP:EventHandler(e, true, false, ...)
end)

function PUP:EventHandler(e, wowevent, internal, ...) -- internal checks whether the event comes from addon comms. We don't want to allow blizzard events to be fired manually
    if e == "NSAPI_SPEC" then -- Should technically rename to "NSI_SPEC" but need to keep this open for the global broadcast to be compatible with the database WA
        local unit, spec = ...
        PUP.specs = PUP.specs or {}
        PUP.specs[unit] = tonumber(spec)
        NSAPI.HasNSRT = NSAPI.HasNSRT or {}
        NSAPI.HasNSRT[unit] = true
    elseif e == "NSAPI_SPEC_REQUEST" then
        local specid = GetSpecializationInfo(GetSpecialization())
        NSAPI:Broadcast("NSAPI_SPEC", "RAID", specid)
    elseif e == "ENCOUNTER_START" and (wowevent and PUP:Difficultycheck(false, 14)) then -- allow sending fake encounter_start if in debug mode, only send spec info in mythic, heroic and normal raids
        PUP.specs = {}
        NSAPI.HasNSRT = {}
        for u in PUP:IterateGroupMembers() do
            if UnitIsVisible(u) then
                NSAPI.HasNSRT[u] = false
                PUP.specs[u] = WeakAuras.SpecForUnit(u)
            end
        end
        -- broadcast spec info
        local specid = GetSpecializationInfo(GetSpecialization())
        NSAPI:Broadcast("NSAPI_SPEC", "RAID", specid)
        C_Timer.After(0.5, function()
            WeakAuras.ScanEvents("NSAPI_ENCOUNTER_START", true)
        end)
    end
end
