--Myth-style casualty announcing for funsies! OnUpdate starts when someone dies and stops when you zone

local _, Obituary = ...
local module = Obituary:NewModule("Announcer", "AceEvent-3.0")

local db
local deaths = 0
local total = 0

local announcer = CreateFrame("Frame")
announcer:Hide()
announcer:SetScript("OnUpdate", function(self, elapsed)
	total = total + elapsed
	if total > 1.6 then
		total = total - 1.6
		if deaths == 0 then return end

		--if summaries are enabled, then we check for throttling and use the wipe sound if it's hit
		if deaths > 3 and db.summary and db.throttle then
			PlaySoundFile([[Interface\AddOns\ObituaryN\Sounds\massivecasualties.ogg]], "Master")
			total = -10
		elseif deaths > 4 and (not db.summary or (db.summary and not db.throttle)) then
			PlaySoundFile([[Interface\AddOns\ObituaryN\Sounds\massivecasualties.ogg]], "Master")
		elseif deaths > 1 then
			PlaySoundFile([[Interface\AddOns\ObituaryN\Sounds\casualties.ogg]], "Master")
		elseif deaths > 0 then
			PlaySoundFile([[Interface\AddOns\ObituaryN\Sounds\casualty.ogg]], "Master")
		end

		deaths = 0
	elseif total < 0 then
		--so deaths don't accumulate while we're throttled (wiping)
		deaths = 0
	end
end)

local function StopAnnouncer()
	announcer:Hide()
	total = 0
	deaths = 0
end

function module:Death()
	if not self:IsEnabled() then return end
	announcer:Show()
	deaths = deaths + 1
end


function module:OnInitialize()
	db = Obituary.db.profile

	local function OnProfileChanged()
		StopAnnouncer()
		db = Obituary.db.profile
	end
	Obituary.db.RegisterCallback(self, "OnProfileChanged", OnProfileChanged)
	Obituary.db.RegisterCallback(self, "OnProfileCopied", OnProfileChanged)
	Obituary.db.RegisterCallback(self, "OnProfileReset", OnProfileChanged)

	self:SetEnabledState(db.announceDeath)
end

function module:OnEnable()
	self:RegisterEvent("PLAYER_ENTERING_WORLD", StopAnnouncer)
	self:RegisterEvent("ZONE_CHANGED_NEW_AREA", StopAnnouncer)

	self:RegisterMessage("Obituary_PlayerDeath", "Death")
end

function module:OnDisable()
	StopAnnouncer()
end