-- 버전 체크 모듈
local IRF2 = InvenRaidFrames2

local _G = _G
local select = _G.select
local tonumber = _G.tonumber
local floor = _G.math.floor
local GetTime = _G.GetTime
local IsInGuild = _G.IsInGuild
local IsInInstance = _G.IsInInstance
local SendAddonMessage = _G.SendAddonMessage
local GetNumRaidMembers = _G.GetNumRaidMembers
local GetNumPartyMembers = _G.GetNumPartyMembers

local chkTimer, ver, numver, strver, major, minor, subver, sendType, ins = 0
local lastCheckTime = 0


function IRF2:SendVersionMessage(forceSendType)
	if lastCheckTime <= GetTime() then
		lastCheckTime = GetTime() + 5
		if forceSendType == "GUILD" then
			if IsInGuild() then
				SendAddonMessage("IRF2", ("%s@%d"):format(self.version, self.numberVersion), "GUILD")
			end
		else
			ins = select(2, IsInInstance())
			if ins == "pvp" or ins == "arena" then
				SendAddonMessage("IRF2", ("%s@%d"):format(self.version, self.numberVersion), "BATTLEGROUND")
			elseif GetNumRaidMembers() > 0 then
				SendAddonMessage("IRF2", ("%s@%d"):format(self.version, self.numberVersion), "RAID")
			elseif GetNumPartyMembers() > 0 then
				SendAddonMessage("IRF2", ("%s@%d"):format(self.version, self.numberVersion), "PARTY")
			end
		end
	end
end

function IRF2:CHAT_MSG_ADDON(prefix, msg, sendType, sender)
	if prefix == "IRF2" and sender ~= self.playerFullName then
		if msg == "CHECKVERSION" then
			self:SendVersionMessage(sendType)
		else
			ver, numver = msg:match("(.+)@(%d+)$")
			if ver and numver then
				numver = tonumber(numver)
				if chkTimer >= GetTime() then
					if self.numberVersion == numver then
						self:Message(("[%s] v%s"):format(sender, ver))
					elseif self.numberVersion > numver then
						self:Message(("[%s] |cffff5858v%s|r"):format(sender, ver))
					else
						self:Message(("[%s] |cff00ff00v%s|r"):format(sender, ver))
					end
				end
				if self.newVersion < numver then
					-- 처음 접속이나 파티 혹은 공격대 참여시 새버전 확인
					self.newVersion = numver
					self:Message(("새 버전이 발견되었습니다. (새 버전: %s)"):format(ver))
				end
			end
		end
	end
end

function IRF2:ConvertVersion(v)
	if v then
		major = floor(v / 10000)
		minor = floor((v - major * 10000) / 100)
		subver = v - major * 10000 - minor * 100
		return ("%d.%d.%d"):format(major, minor, subver)
	end
end

function IRF2:VersionCheck()
	if chkTimer < GetTime() then
		chkTimer = GetTime() + 2
		IRF2:Message("버전 확인을 시작합니다.")
		self:Message(("[%s] v%s"):format(self.playerFullName, IRF2.version))
		ins = select(2, IsInInstance())
		if ins == "pvp" or ins == "arena" then
			SendAddonMessage("IRF2", "CHECKVERSION", "BATTLEGROUND")
		elseif GetNumRaidMembers() > 0 then
			SendAddonMessage("IRF2", "CHECKVERSION", "RAID")
		elseif GetNumPartyMembers() > 0 then
			SendAddonMessage("IRF2", "CHECKVERSION", "PARTY")
		else

		end
	end
end