local RaidComm = LibStub("LibRaidComm-1.0", true)
if not RaidComm then
	InvenRaidFrames3Member_UpdateResurrection = function() end
	InvenRaidFrames3Member_OnUpdateResurrectionBar = InvenRaidFrames3Member_UpdateResurrection
	return
end

local _G = _G
local IRF3 = _G[...]
local pairs = _G.pairs
local wipe = _G.table.wipe
local GetTime = _G.GetTime
local UnitInRaid = _G.UnitInRaid
local UnitInParty = _G.UnitInParty
local UnitCastingInfo = _G.UnitCastingInfo
local function UnitInGroup(unit)
	return UnitInRaid(unit) or UnitInParty(unit)
end
local resUnits, casters, castName, castStart, castEnd = {}, {}
local delimiter = ","

function InvenRaidFrames3Member_OnUpdateResurrectionBar(self)
	casters[1], casters[2], casters[3], casters[4], casters[5] = delimiter:split(self.caster)
	self.startTime, self.endTime = nil
	for _, caster in pairs(casters) do
		castName, _, _, _, castStart, castEnd = UnitCastingInfo(caster)
		if RaidComm.resurrectionSpells[castName] then
			if not self.endTime or self.endTime < castEnd then
				self.startTime, self.endTime = castStart, castEnd
			end
		end
	end
	if self.startTime then
		self:SetMinMaxValues(self.startTime, self.endTime)
		self:SetValue(GetTime() * 1000)
	else
		self.caster = nil
		self:Hide()
	end
end

function InvenRaidFrames3Member_UpdateResurrection(self)
	if self.isGhost or self.isDead then
		self.resurrectionBar.caster = resUnits[RaidComm:GetUnitName(self.displayedUnit)]
		if self.resurrectionBar.caster then
			self.resurrectionBar:Show()
		else
			self.resurrectionBar:Hide()
		end
	else
		self.resurrectionBar.caster = nil
		self.resurrectionBar:Hide()
	end
end

local eventHandler = CreateFrame("Frame")
eventHandler:SetScript("OnEvent", function(self, event, unit, spell)
	if RaidComm.resurrectionSpells[spell] then
		wipe(resUnits)
		for caster, target in pairs(RaidComm.castingTarget) do
			if UnitInGroup(caster) and UnitInGroup(target) then
				if resUnits[target] then
					resUnits[target] = resUnits[target]..","..caster
				else
					resUnits[target] = caster
				end
			end
		end
		for member in pairs(IRF3.visibleMembers) do
			if member.resurrectionBar then
				InvenRaidFrames3Member_UpdateResurrection(member)
			end
		end
	end
end)
eventHandler:RegisterEvent("UNIT_SPELLCAST_START")
eventHandler:RegisterEvent("UNIT_SPELLCAST_STOP")