local _G = _G
local pairs = _G.pairs
local GetTime = _G.GetTime
local UnitBuff = _G.UnitBuff
local IRF3 = _G[...]

-- 직업별 생존기 정의 (*는 타인에게 걸 수 있는 생존기)
local SL = IRF3.GetSpellName
local skills = {
	["WARRIOR"] = { [SL(871)] = "방벽", [SL(12975)] = "최저" },
	["ROGUE"] = { [SL(5277)] = "회피", [SL(31224)] = "그망" },
	["PALADIN"] = { [SL(642)] = "무적", [SL(498)] = "가호", [SL(31850)] = "헌수" },
	["MAGE"] = { [SL(27619)] = "얼방", [SL(66)] = "투명" },
	["HUNTER"] = { [SL(5384)] = "죽척", [SL(19263)] = "저지" },
	["PRIEST"] = { [SL(27827)] = "구원", [SL(47585)] = "분산" },
	["DRUID"] = { [SL(61336)] = "생본", [SL(22812)] = "껍질", [SL(22842)] = "광포" },
	["DEATHKNIGHT"] = { [SL(48792)] = "얼인", [SL(51271)] = "불굴", [SL(49039)] = "리치", [SL(55233)] = "흡혈" },
	["SHAMAN"] = { [SL(30823)] = "주분" },
	["*"] = { [SL(1022)] = "보손", [SL(47788)] = "수호", [SL(33206)] = "고억", [SL(6940)] = "희손" },
}
local ignoreEndTime = { [SL(19752)] = true, [SL(5834)] = true, [SL(66)] = true }
for _, v in pairs(skills) do
	v[""] = nil
end
ignoreEndTime[""] = nil

local name, survival, endTime, prevTime, ctime

local function checkSkill(unit, class)
	-- 타인에게 걸 수 있는 생존기 체크
	for spell, newText in pairs(skills["*"]) do
		name, _, _, _, _, _, endTime = UnitBuff(unit, spell)
		if name then
			return newText, (not ignoreEndTime[spell] and endTime and endTime > 0) and endTime
		end
	end
	-- 직업별 자체 생존기 체크
	if skills[class] then
		for spell, newText in pairs(skills[class]) do
			name, _, _, _, _, _, endTime = UnitBuff(unit, spell)
			if name then
				return newText, (not ignoreEndTime[spell] and endTime and endTime > 0) and endTime
			end
		end
	end
	return nil
end

function InvenRaidFrames3Member_UpdateSurvivalSkill(self)
	if IRF3.db.units.useSurvivalSkill then
		self.survivalSkill, self.survivalSkillEndTime = checkSkill(self.displayedUnit, self.class)
		self.survivalSkillTimeLeft = ""
	else
		self.survivalSkill, self.survivalSkillEndTime, self.survivalSkillTimeLeft = nil
	end
end

function InvenRaidFrames3Member_OnUpdateSurvivalSkill(self)
	if IRF3.db.units.useSurvivalSkill and self.survivalSkillEndTime and IRF3.db.units.showSurvivalSkillTimer then
		prevTime, ctime = self.survivalSkillTimeLeft, GetTime()
		if self.survivalSkillEndTime < ctime then
			self.survivalSkill, self.survivalSkillEndTime, self.survivalSkillTimeLeft = nil
		else
			self.survivalSkillTimeLeft = (":%d"):format(self.survivalSkillEndTime - ctime + 0.5)
		end
		if prevTime ~= self.survivalSkillTimeLeft then
			InvenRaidFrames3Member_UpdateDisplayText(self)
		end
	end
end