
-------------------------------------
-- 查看UNIT装备等级 Author: M
-------------------------------------

local _, LibItem = ...

--物品列表框架
local function ItemListFrame(parent)
    if (not parent.eqlist) then
        parent.eqlist = CreateFrame("Frame", nil, parent)
        parent.eqlist:SetSize(246, 424)
        parent.eqlist:SetBackdrop({
            bgFile = "Interface\\Tooltips\\UI-Tooltip-Background", edgeFile = "Interface\\Tooltips\\UI-Tooltip-Border",
            tile = true, tileSize = 8, edgeSize = 16, insets = {left = 4, right = 4, top = 4, bottom = 4}
        })
        parent.eqlist:SetBackdropBorderColor(1, 1, 1)
        parent.eqlist:SetBackdropColor(0, 0, 0)
        parent.eqlist:SetPoint("TOPLEFT", parent, "TOPRIGHT", 2, 0)
        parent.eqlist.title = parent.eqlist:CreateFontString(nil, "ARTWORK", "GameFontNormalLargeOutline")
        parent.eqlist.title:SetPoint("TOPLEFT", parent.eqlist, "TOPLEFT", 66, -18)
        parent.eqlist.PortraitFrame = CreateFrame("Frame", nil, parent.eqlist, "GarrisonFollowerPortraitTemplate")
        parent.eqlist.PortraitFrame:SetPoint("TOPLEFT", parent.eqlist, "TOPLEFT", 18, -16)
        parent.eqlist.PortraitFrame:SetScale(0.8)
        for i = 0, 16 do
            parent.eqlist["item"..i] = parent.eqlist:CreateFontString(nil, "ARTWORK", "GameTooltipText")
            if (i == 0) then
                parent.eqlist["item"..i]:SetFont(GameTooltipText:GetFont(), 13, "THINOUTLINE")
            end
            parent.eqlist["item"..i]:SetPoint("TOPLEFT", parent.eqlist["item"..(i-1)] or parent.eqlist.title, "BOTTOMLEFT", i==1 and -12 or 0, i==1 and -16 or -8)
        end
        local slots = {
            HEADSLOT, NECKSLOT, SHOULDERSLOT, CHESTSLOT, WAISTSLOT, LEGSSLOT, FEETSLOT, WRISTSLOT, HANDSSLOT,
            FINGER0SLOT, FINGER1SLOT, TRINKET0SLOT, TRINKET1SLOT, BACKSLOT, MAINHANDSLOT, SECONDARYHANDSLOT
        }
        local fontsize = GetLocale():sub(1,2) == "zh" and 12 or 8
        for i, v in ipairs(slots) do
            parent.eqlist["slot"..i] = CreateFrame("Frame", nil, parent.eqlist)
            parent.eqlist["slot"..i]:SetSize(36, 17)
            parent.eqlist["slot"..i]:SetBackdrop({
                bgFile = "Interface\\Tooltips\\UI-Tooltip-Background",
                edgeFile = "Interface\\Tooltips\\UI-Tooltip-Border", tile = true, tileSize = 8, edgeSize = 8,
                insets = { left = 1, right = 1, top = 1, bottom = 1 }
            })
            parent.eqlist["slot"..i]:SetBackdropBorderColor(0, 0.8, 0.8, 0.4)
            parent.eqlist["slot"..i]:SetBackdropColor(0, 0.9, 0.9, 0.3)
            parent.eqlist["slot"..i]:SetPoint("RIGHT", parent.eqlist["item"..i], "LEFT", -3, 0)
            parent.eqlist["slot"..i].title = parent.eqlist["slot"..i]:CreateFontString(nil, "ARTWORK")
            parent.eqlist["slot"..i].title:SetFont(UNIT_NAME_FONT, fontsize, "THINOUTLINE")
            parent.eqlist["slot"..i].title:SetSize(36, 14)
            parent.eqlist["slot"..i].title:SetPoint("CENTER", 1, 0)
            parent.eqlist["slot"..i].title:SetText(v)
            parent.eqlist["slot"..i].title:SetTextColor(0,1,1,0.9)
            parent.eqlist["slot"..i]:SetScript("OnEnter", function(self)
                self:SetBackdropColor(0, 0.9, 0.9, 1)
            end)
            parent.eqlist["slot"..i]:SetScript("OnLeave", function(self)
                self:SetBackdropColor(0, 0.9, 0.9, 0.3)
            end)
        end
        parent:HookScript("OnHide", function(self) self.eqlist:Hide() end)
        GearManagerDialogPopup:SetFrameLevel(parent.eqlist:GetFrameLevel()+10)
    end
    return parent.eqlist
end

--显示天赋
local function ShowSpecialization(unit, frame)
    if (not frame.specicon) then
        frame.specicon = frame:CreateTexture(nil, "BORDER")
        frame.specicon:SetSize(42, 42)
        frame.specicon:SetPoint("TOPRIGHT", -5, -5)
        frame.specicon:SetAlpha(0.3)
        frame.specicon:SetMask("Interface\\Minimap\\UI-Minimap-Background")
        frame.spectext = frame:CreateFontString(nil, "BORDER")
        frame.spectext:SetFont(SystemFont_Outline_Small:GetFont(), 10, "THINOUTLINE")
        frame.spectext:SetPoint("BOTTOM", frame.specicon, "BOTTOM")
        frame.spectext:SetJustifyH("CENTER")
        frame.spectext:SetAlpha(0.5)
    end
    local _, specID, specName, specIcon
    if (unit == "player") then
        specID = GetSpecialization()
        _, specName, _, specIcon = GetSpecializationInfo(specID)
    else
        specID = GetInspectSpecialization(unit)
        _, specName, _, specIcon = GetSpecializationInfoByID(specID)
    end
    if (specIcon) then
        frame.spectext:SetText(specName)
        frame.specicon:SetTexture(specIcon)
        frame.specicon:Show()
    else
        frame.spectext:SetText("")
        frame.specicon:Hide()
    end
end

--寶石附魔: 創建圖標框体
local function CreateIconFrame(self, index)
    local icon = CreateFrame("Frame", nil, self)
    icon:Hide()
    icon:SetSize(16, 16)
    icon:SetScript("OnEnter", function(self)
        if (self.title) then
            GameTooltip:SetOwner(self, "ANCHOR_RIGHT")
            GameTooltip:SetText(self.title)
            GameTooltip:Show()
        elseif (self.itemLink) then
            GameTooltip:SetOwner(self, "ANCHOR_RIGHT")
            GameTooltip:SetHyperlink(self.itemLink)
            GameTooltip:Show()
        elseif (self.spellID) then
            GameTooltip:SetOwner(self, "ANCHOR_RIGHT")
            GameTooltip:SetSpellByID(self.spellID)
            GameTooltip:Show()
        end
    end)
    icon:SetScript("OnLeave", function(self)
        GameTooltip:Hide()
    end)
    icon.bg = icon:CreateTexture(nil, "BACKGROUND")
    icon.bg:SetSize(16, 16)
    icon.bg:SetPoint("CENTER")
    icon.bg:SetTexture("Interface\\Common\\RingBorder")
    icon.texture = icon:CreateTexture(nil, "BORDER")
    icon.texture:SetSize(12, 12)
    icon.texture:SetPoint("CENTER")
    icon.texture:SetMask("Interface\\Minimap\\UI-Minimap-Background")
    self["xicon"..index] = icon
    return self["xicon"..index]
end

--寶石附魔: 找出可用圖標
local function GetIconFrame(self)
    local index = 1
    while (self["xicon"..index]) do
        if (not self["xicon"..index]:IsShown()) then
            return self["xicon"..index]
        end
        index = index + 1
    end
    return CreateIconFrame(self, index)
end

--寶石附魔: 隱藏所有圖標
local function HideIconFrame(self)
    local index = 1 
    while (self["xicon"..index]) do
        self["xicon"..index].title = nil
        self["xicon"..index].itemLink = nil
        self["xicon"..index].spellID = nil
        self["xicon"..index]:Hide()
        index = index + 1
    end
end

--寶石附魔: 獲取寶石槽數量
local function GetGemNumber(ItemLink)
    local stats = GetItemStats(ItemLink)
    local num = (stats["EMPTY_SOCKET_RED"] or 0)
                + (stats["EMPTY_SOCKET_BLUE"] or 0)
                + (stats["EMPTY_SOCKET_META"] or 0)
                + (stats["EMPTY_SOCKET_YELLOW"] or 0)
                + (stats["EMPTY_SOCKET_PRISMATIC"] or 0)
    return num
end

--寶石附魔: 顯示
local function ShowGemAndEnchant(self, ItemLink, anchorFrame)
    local _, link, quality, texture, icon
    local num = 0
    --已有寶石
    for i = 1, 3 do
        _, link = GetItemGem(ItemLink, i)
        if (link) then
            _,_,quality,_,_,_,_,_,_,texture = GetItemInfo(link)
            if (texture) then
                local r, g, b = GetItemQualityColor(quality)
                icon = GetIconFrame(self)
                icon.itemLink = link
                icon.bg:SetVertexColor(r,g,b)
                icon.texture:SetTexture(texture)
                icon:Show()
                icon:ClearAllPoints()
                icon:SetPoint("LEFT", anchorFrame, "RIGHT", num == 0 and 6 or 1, 0)
                anchorFrame = icon
                num = num + 1
            end
        end
    end
    --空槽
    for i = num, GetGemNumber(ItemLink)-1 do
        icon = GetIconFrame(self)
        icon.title = EMPTY or "Empty"
        icon.bg:SetVertexColor(1,1,1,0.4)
        icon.texture:SetTexture("Interface\\Cursor\\Quest")
        icon:Show()
        icon:ClearAllPoints()
        icon:SetPoint("LEFT", anchorFrame, "RIGHT", num == 0 and 6 or 1, 0)
        anchorFrame = icon
        num = num + 1
    end
    --附魔
    local enchant = tonumber(string.match(ItemLink, "item:%d+:(%d+):"))
    if (enchant) then
        icon = GetIconFrame(self)
        if (TinyEnchantItemDB and TinyEnchantItemDB[enchant]) then
            _,link,quality,_,_,_,_,_,_,texture = GetItemInfo(TinyEnchantItemDB[enchant])
            icon.itemLink = link
            icon.bg:SetVertexColor(1,1,1)
            icon.texture:SetTexture(texture)
            icon:Show()
            icon:ClearAllPoints()
            icon:SetPoint("LEFT", anchorFrame, "RIGHT", num == 0 and 6 or 1, 0)
            num = num + 1
        elseif (TinyEnchantSpellDB and TinyEnchantSpellDB[enchant]) then
            _, _, texture = GetSpellInfo(TinyEnchantSpellDB[enchant])
            icon.spellID = TinyEnchantSpellDB[enchant]
            icon.bg:SetVertexColor(1,1,1)
            icon.texture:SetTexture(texture)
            icon:Show()
            icon:ClearAllPoints()
            icon:SetPoint("LEFT", anchorFrame, "RIGHT", num == 0 and 6 or 1, 0)
            num = num + 1
        end
    end
    return num * 18
end

--显示物品列表
local function ShowItemList(unit, equippedLevel, parent)
    local frame = ItemListFrame(parent or UIParent)
    local class = select(2,UnitClass(unit))
    local color = RAID_CLASS_COLORS[class] or NORMAL_FONT_COLOR
    ShowSpecialization(unit, frame)
    frame:SetBackdropBorderColor(color.r, color.g, color.b)
    frame.title:SetText(UnitName(unit))
    frame.title:SetTextColor(color.r, color.g, color.b)
    frame.PortraitFrame:SetLevel(UnitLevel(unit))
    frame.PortraitFrame.PortraitRingQuality:SetVertexColor(color.r, color.g, color.b)
    frame.PortraitFrame.LevelBorder:SetVertexColor(color.r, color.g, color.b)
    SetPortraitTexture(frame.PortraitFrame.Portrait, unit)
    frame.item0:SetText(format(ITEM_LEVEL, equippedLevel))
    frame.item0:SetTextColor(1, 0.82, 0)
    local width, iconWidth = 160, 0
    local _, level, link, quality, mainhand, mainlink, mainquality
    local i, index = 1, 1
    HideIconFrame(frame)
    while (i <= 16) do
        index = i >= 4 and i+1 or i
        _, level, _, link, quality = LibItem:GetUnitItemInfo(unit, index)
        if (index == 16) then
            mainhand = level
            mainlink = link
            mainquality = quality
        end
        if (level > 0) then
            frame["item"..i]:SetText(format("%3d",level) .. link)
            iconWidth = ShowGemAndEnchant(frame, link, frame["item"..i])
            if (width < frame["item"..i]:GetWidth() + iconWidth) then
                width = frame["item"..i]:GetWidth() + iconWidth
            end
        else
            frame["item"..i]:SetText(" ")
        end
        i = i + 1
    end
    if (link and mainquality == 6) then
        level = max(mainhand, level)
        frame.item15:SetText(format("%3d",level) .. mainlink)
        frame.item16:SetText(format("%3d",level) .. link)
    end
    frame:SetWidth(width + 70)
    if (frame:GetParent():IsShown()) then frame:Show() end
end

--显示观察目标物品列表
local function ShowInspectItemList()
    if (not InspectFrame.eqlevel) then
        InspectFrame.eqlevel = InspectPaperDollFrame:CreateFontString(nil, "OVERLAY", "GameFontNormalSmall")
        InspectFrame.eqlevel:SetPoint("RIGHT", InspectFrame.TitleText, "RIGHT", 48, -38)
        InspectFrame.eqlevel:SetJustifyH("RIGHT")
        InspectFrame.eqlevel:SetTextColor(0, 0.8, 0.8)
    end
    LibItem:AddTask({
        identity  = UnitGUID(InspectFrame.unit),
        timer     = 0.6,
        elasped   = 0.76,
        expired   = GetTime() + 4,
        onStart   = function(self) InspectFrame.eqlevel:SetText("Reading...") end,
        onTimeout = function(self) InspectFrame.eqlevel:SetText("Failed") end,
        onExecute = function(self)
            if (not InspectFrame.unit or self.identity ~= UnitGUID(InspectFrame.unit)) then return end
            local unknownCount, equippedLevel = LibItem:GetUnitItemLevel(InspectFrame.unit)
            if (unknownCount == 0) then
                InspectFrame.eqlevel:SetText(format(STAT_AVERAGE_ITEM_LEVEL_EQUIPPED, equippedLevel))
                ShowItemList(InspectFrame.unit, equippedLevel, InspectFrame)
                LibItem:AwakeTask("Inspect.+Slot", true)
                return true
            end
        end,
    })
end

--自己面板顯示
hooksecurefunc("PaperDollFrame_SetItemLevel", function(statFrame, unit)
    ShowItemList("player", select(2,GetAverageItemLevel()), PaperDollFrame)
end)

--觀察目標顯示
local frame = CreateFrame("Frame", nil, UIParent)
frame:RegisterEvent("ADDON_LOADED")
frame:RegisterEvent("UNIT_INVENTORY_CHANGED")
frame:SetScript("OnEvent", function(self, event, arg1)
    if (event == "ADDON_LOADED" and arg1 == "Blizzard_InspectUI") then
        hooksecurefunc("InspectFrame_UpdateTabs", function()
            if (not InspectFrame.unit) then return end
            ShowInspectItemList()
        end)
        self:UnregisterEvent("ADDON_LOADED")
    elseif (event == "UNIT_INVENTORY_CHANGED") then
        if (InspectFrame and arg1 == InspectFrame.unit) then
            ShowInspectItemList()
        end
    end
end)
