-- 사용자 주문 타이머
local IRF2 = InvenRaidFrames2

local _G = _G
local type = _G.type
local pairs = _G.pairs
local select = _G.select
local max = _G.math.max
local ceil = _G.math.ceil
local tinsert = _G.table.insert
local UnitAura = _G.UnitAura
local UnitIsUnit = _G.UnitIsUnit

local auraFilterPlayer = {
	["자신이 시전한 버프"] = "HELPFUL|PLAYER",
}

local auraFilter = {
	["버프"] = "HELPFUL",
	["디버프"] = "HARMFUL",
}

local userSpellTimerHandler = CreateFrame("Frame")

local initTimer, timerNames, ready = 0, {}, {}
local name, icon, count, timeLeft, isMine, pos
local iconSize = 13

local function isShown(index)
	if InvenRaidFrames2CharDB.userSpellTimer.auraNames[index] ~= "" and InvenRaidFrames2CharDB.userSpellTimer.auraTypes[index] ~= "사용 안함" then
		return true
	end
	return nil
end

local function OnUpdate(self, timer)
	self.timer = self.timer + timer
	if self.timer >= 0.1 then
		self.timer = 0
		self.hideTime = self.timeLeft - GetTime()
		self.prev_timerLength = self.timerLength
		if self.hideTime > 0 and self.hideTime < 9 then
			-- 타이머 숫자 한 자
			self.timerLength = 9
			self.cooldown:SetText(ceil(self.hideTime))

		elseif self.hideTime > 9 and self.hideTime < 100 then
			-- 타이머 숫자 두 자
			self.timerLength = 18
			self.cooldown:SetText(ceil(self.hideTime))
		else
			-- 타이머 숫자 없음
			self.timerLength = 0
			self.cooldown:SetText("")
		end
		if self.prev_timerLength ~= self.timerLength then
			self:SetWidth(iconSize + self.timerLength)
		end
	end
end

local function OnHide(self)
	self.timeLeft = nil
	self.hideTime = nil
	self.prev_timerLength = nil
	self.timer = 0
end

local function CreateSpellTimer(object, index)
	if not object.userSpellTimer[index] then
		object.userSpellTimer[index] = CreateFrame("Frame", nil, object)
		object.userSpellTimer[index]:Hide()
		object.userSpellTimer[index]:SetID(index)
		object.userSpellTimer[index]:SetScale(InvenRaidFrames2CharDB.userSpellTimer.scale)
		object.userSpellTimer[index]:SetWidth(0.01)
		object.userSpellTimer[index]:SetHeight(iconSize)
		object.userSpellTimer[index]:SetFrameLevel(IRF2.db.frameLevel.spellTimer)
		object.userSpellTimer[index].timer = 0
		object.userSpellTimer[index].icon = object.userSpellTimer[index]:CreateTexture(nil, "ARTWORK")
		object.userSpellTimer[index].icon:SetPoint("LEFT", object.userSpellTimer[index], "LEFT")
		object.userSpellTimer[index].icon:SetWidth(iconSize)
		object.userSpellTimer[index].icon:SetHeight(iconSize)
		object.userSpellTimer[index].count = object.userSpellTimer[index]:CreateFontString(nil, "OVERLAY", "NumberFontNormalSmall")
		object.userSpellTimer[index].count:SetPoint("CENTER", object.userSpellTimer[index].icon, "CENTER", 2, 0)
		object.userSpellTimer[index].cooldown = object.userSpellTimer[index]:CreateFontString(nil, "OVERLAY", "GameFontNormal")
		object.userSpellTimer[index].cooldown:SetTextColor(1, 1, 1)
		object.userSpellTimer[index].cooldown:SetPoint("LEFT", object.userSpellTimer[index].icon, "RIGHT", 0, 1)
		object.userSpellTimer[index]:SetScript("OnUpdate", OnUpdate)
		object.userSpellTimer[index]:SetScript("OnHide", OnHide)
		pos = IRF2:GetFramePoint(InvenRaidFrames2CharDB.userSpellTimer.auraPos[index])
		object.userSpellTimer[index]:SetPoint(pos[1], object, pos[2], pos[3])
	end
end

local function userSpellTimer(object)
	for i, auraType in ipairs(InvenRaidFrames2CharDB.userSpellTimer.auraTypes) do
		if isShown(i) then
			name, icon, count, timeLeft = nil
			-- 자신이 시전한 주문 검색
			if auraFilterPlayer[auraType] then
				name, _, icon, count, _, _, timeLeft, ownerUnit = UnitAura(object.vehicleUnit or object.unit, InvenRaidFrames2CharDB.userSpellTimer.auraNames[i], nil, auraFilterPlayer[auraType])
				if name == InvenRaidFrames2CharDB.userSpellTimer.auraNames[i] and (ownerUnit == 1 or (type(ownerUnit) == "string" and UnitIsUnit("player", ownerUnit))) then
					ownerUnit = true
				else
					name, ownerUnit = nil, nil
				end
			end
			-- 타인이 시전한 주문 검색
			if not name and auraFilter[auraType] then
				name, _, icon, count, _, _, timeLeft = UnitAura(object.vehicleUnit or object.unit, InvenRaidFrames2CharDB.userSpellTimer.auraNames[i], nil, auraFilter[auraType])
				if name ~= InvenRaidFrames2CharDB.userSpellTimer.auraNames[i] then
					name = nil
				end
			end
			if name then
				object.userSpellTimer = object.userSpellTimer or {}
				CreateSpellTimer(object, i)
				object.userSpellTimer[i].icon:SetTexture(icon)
				object.userSpellTimer[i].timeLeft = timeLeft or 0
				if InvenRaidFrames2CharDB.userSpellTimer.icon[i] then
					object.userSpellTimer[i].count:SetText((count and count > 1) and count or "")
				else
					object.userSpellTimer[i].count:SetText("")
				end
				OnUpdate(object.userSpellTimer[i], 1)
				object.userSpellTimer[i]:Show()
			elseif object.userSpellTimer and object.userSpellTimer[i] and object.userSpellTimer[i]:IsShown() then
				object.userSpellTimer[i]:Hide()
			end
		elseif object.userSpellTimer and object.userSpellTimer[i] and object.userSpellTimer[i]:IsShown() then
			object.userSpellTimer[i]:Hide()
		end
	end
end

userSpellTimerHandler:SetScript("OnEvent", function(self, event, unit)
	IRF2:RunUnitFunction(unit, userSpellTimer)
end)

local function userSpellTimerMod(object)
	IRF2.objectModules["UserSpellTimer"] = nil
	IRF2:RegisterAuraEvent("UserSpellTimer", userSpellTimer)
	IRF2:SetupUserSpellTimer()
end

IRF2:RegisterObjectModule("UserSpellTimer", userSpellTimerMod)

function IRF2:SetupUserSpellTimer()
	for i = 1, #InvenRaidFrames2CharDB.userSpellTimer.auraTypes do
		if isShown(i) then
			userSpellTimerHandler:RegisterEvent("UNIT_AURA")
			return
		end
	end
	userSpellTimerHandler:UnregisterEvent("UNIT_AURA")
end