local addonName, ns = ...
local _G = _G

local itemslots = {
	"HeadSlot",
	"NeckSlot",
	"ShoulderSlot",
	"BackSlot",
	"ChestSlot",
	"WristSlot",
	"MainHandSlot",
	"SecondaryHandSlot",
	"HandsSlot",
	"WaistSlot",
	"LegsSlot",
	"FeetSlot",
	"Finger0Slot",
	"Finger1Slot",
	"Trinket0Slot",
	"Trinket1Slot",
}

local ToMainHand = {
	"134553", -- 분노 전사
	"128479", -- 잠행 도적
	"128869", -- 암살 도적
	"134552", -- 무법 도적
	"133958", -- 암흑 사제
	"133959", -- 화염 법사
	"128822", -- 수호 드루
	"128859", -- 야성 드루
	"128873", -- 고양 술사
	"128936", -- 정기 술사
	"128934", -- 복원 술사
	"128293", -- 냉기 죽기
	"133948", -- 풍운 수도
	"128831", -- 복수 악사
	"127830", -- 파멸 악사	
}

local ToSecondHand = {
	"128288", -- 방어 전사
	"137246", -- 악마 흑마
	"128867", -- 보호 기사
}

local fontstrings = {}
-- AVERAGE
local frame = CreateFrame("Frame", "SSItemLevel", UIParent)
frame.scanTooltip = CreateFrame("GameTooltip", "SSItemLevel_ScanTip", nil, "GameTooltipTemplate");
frame.scanTooltip:SetOwner(UIParent, "ANCHOR_NONE");
frame.itemslots = itemslots
local msg = string.gsub(ITEM_LEVEL, "%%d", "(.+)")
local msg2 = string.gsub(ITEM_LEVEL, "%%d", "(.+) \((.+)\)")

ns.SSItemLevel = frame

frame:SetScript("OnEvent", function(self, event, ...) self[event](self, ...) end)

function frame:CheckItemLevelTextOverride()
		if (IsAddOnLoaded("DejaCharacterStats")) then
			return false
		end
		if (UnitLevel("player") < MIN_PLAYER_LEVEL_FOR_ITEM_LEVEL_DISPLAY) then
			return false
		end
		return true
end

function frame:GetScanItemLevel(unit, slot)
	self.scanTooltip:ClearLines()
	self.scanTooltip:SetOwner(UIParent, "ANCHOR_NONE")
	local hasItem = self.scanTooltip:SetInventoryItem(unit, slot)
	self.scanTooltip:Show()

	if hasItem then
		local numLines = self.scanTooltip:NumLines();
		local iLevel = 0
		for i = 2, min(numLines, 5) do
			local text = _G["SSItemLevel_ScanTipTextLeft" .. i]:GetText() or ""
			local iLevel = string.match(text, msg)
			local iLevel2 = string.match(text, msg2)
			if iLevel ~= nil then
				local retval = tonumber(iLevel)
				if(retval ~= nil) then
					self.scanTooltip:Hide()
					return retval
				else
					local iLevel2 = string.match(text, msg2)
					if iLevel2 ~= nil then
						local retval2 = tonumber(iLevel2)
						if(retval2 ~= nil) then
							self.scanTooltip:Hide()
							return retval2
						end
					end				
				end
			end
		end
	end
	self.scanTooltip:Hide()
	return 0
end

function frame:GetItemLevel(unit, itemLink, unitLevel, slot)
	local _,_,quality = GetItemInfo(itemLink)
	local iLevel = self:GetScanItemLevel(unit, slot)
	
	-- 군단 유물 무기 예외처리
	if quality == 6 then
		local itemId = itemLink:match("item:(%d*):(%d*):(%d*):(%d*):(%d*):(%d*):(%d*):(%-?%d*):(%d*):(%-?%d*):(%d*):(%d*):(%d*)([^|]*)|h%[([^%]]+)%]|h|r")  
		for _, chkId in pairs(ToMainHand) do
			if itemId == chkId then
				iLevel =self:GetScanItemLevel(unit,  GetInventorySlotInfo("MainHandSlot"))
			end
		end		
		for _, chkId in pairs(ToSecondHand) do
			if itemId == chkId then
				iLevel =self:GetScanItemLevel(unit,  GetInventorySlotInfo("SecondaryHandSlot"))
			end
		end		
	end
	
	if not quality or not iLevel then
		return 0;
	end	
	return iLevel;
end

function frame:UpdateItemLevel()
	local count, tot, txt = #self.itemslots, 0, nil
	local mainHandLevel = 0
	for slot,n in pairs(self.itemslots) do
		local id = GetInventorySlotInfo(n)
		local link = GetInventoryItemLink("player", id)
		txt = nil
		if link and link ~= "" then
			local ilevel = self:GetItemLevel("player", link, UnitLevel("player"), id)
			if (ilevel and ilevel > 0) then
				txt = ilevel
				tot = tot + ilevel
				if( n == "MainHandSlot") then mainHandSlot = ilevel end
			end
		elseif (n == "SecondaryHandSlot") then
			link = GetInventoryItemLink("player", GetInventorySlotInfo("MainHandSlot")) -- 주장비
			if link ~= nil and link ~= "" then
				local itemEquipLoc = select(9,GetItemInfo(link))
				if (link and link ~= "" and ("INVTYPE_2HWEAPON" == itemEquipLoc or "INVTYPE_RANGED" == itemEquipLoc or "INVTYPE_RANGEDRIGHT" == itemEquipLoc )) then
--					count = count - 1
					tot = tot + mainHandSlot
				end
			end
		end
		fontstrings[slot]:SetText(txt)
	end
--	print(count, tot, tot/count)
--	ItemAverage = tot/count

	if self:CheckItemLevelTextOverride() then
		if ( CharacterStatsPane.ItemLevelFrame.Label ) then
			CharacterStatsPane.ItemLevelFrame.Label:SetText(format(STAT_FORMAT, STAT_AVERAGE_ITEM_LEVEL));
		end
		CharacterStatsPane.ItemLevelFrame.Value:SetText(format("%.2f", tot/count));
		CharacterStatsPane.ItemLevelFrame.numericValue = tot/count;	
	else
		fontstrings['TOT']:SetText(format("%s: %.2f", ITEMS, tot/count))
	end
end

function frame:ADDON_LOADED(addon)
	if (addonName == addon) then
		local font, _, flags = NumberFontNormal:GetFont()

		for slot,n in pairs(self.itemslots) do
			local gslot = _G["Character"..n]
			fontstrings[slot] = gslot:CreateFontString(nil, "OVERLAY")
			fontstrings[slot]:SetFont(font, 12, flags)
			fontstrings[slot]:SetPoint("TOP", gslot, "TOP", 0, -3)
			fontstrings[slot]:SetTextColor(1,1,1)
		end
		
--		hooksecurefunc(CharacterLevelText, "SetFormattedText", function (self,...)
--			self:SetText(format("%s\n%s: %.2f", self:GetText(), ITEMS, ItemAverage))
--		end)	

	if self:CheckItemLevelTextOverride() then
		hooksecurefunc("PaperDollFrame_SetItemLevel", function ()
		self:UpdateItemLevel()
		end)
	else
		fontstrings['TOT'] = _G["PaperDollFrame"]:CreateFontString(nil, "OVERLAY")
		fontstrings['TOT']:SetFont(CharacterLevelText:GetFont())
		fontstrings['TOT']:SetPoint("TOP", CharacterLevelText, "BOTTOM", 0, -3)
		fontstrings['TOT']:SetTextColor(1,1,0)

		hooksecurefunc("PaperDollFrame_SetLevel", function ()
			local a1, f, a2, x, y = CharacterLevelText:GetPoint()
			CharacterLevelText:SetPoint( a1, f, a2, x, y + 10)
		end)	
	end

		_G["PaperDollFrame"]:HookScript("OnShow", function(self, ...)
			frame:UpdateItemLevel()
			frame:RegisterEvent("UNIT_INVENTORY_CHANGED")
		end)

		_G["PaperDollFrame"]:HookScript("OnHide", function(self, ...)
			frame:UnregisterEvent("UNIT_INVENTORY_CHANGED")
		end)

		self:UpdateItemLevel()
		self:UnregisterEvent("ADDON_LOADED")
		self.ADDON_LOADED = nil
	end
end

function frame:UNIT_INVENTORY_CHANGED(unit)
	if (unit == "player") then
		self:UpdateItemLevel()
	end
end
frame.UPDATE_INVENTORY_DURABILITY = frame.UpdateItemLevel

frame:RegisterEvent("ADDON_LOADED")

--ns.SSItemLevel = SSItemLevel