local E = unpack(select(2, ...)); -- Import: Engine

local module = E:NewModule("DataText_Durability", "AceConsole-3.0", "AceEvent-3.0")

local frame = CreateFrame("Frame", "ChopsUI_DataText_Durability", E.Panels.ChatDataTextContainer1)
frame:SetAllPoints()
frame:EnableMouse(true)
frame:SetFrameStrata("BACKGROUND")
frame:SetFrameLevel(3)
frame:Show()

local text = frame:CreateFontString("ChopsUI_DataText_Durability_Text", "OVERLAY")
text:SetFont(E.Media.Fonts.Normal, E.Settings.UI.DataTexts.FontSize)
text:SetJustifyH("LEFT")

frame.text = text
frame.text:SetAllPoints()

local slots = {
	[1] = {1, "Head", 1000},
	[2] = {3, "Shoulder", 1000},
	[3] = {5, "Chest", 1000},
	[4] = {6, "Waist", 1000},
	[5] = {9, "Wrist", 1000},
	[6] = {10, "Hands", 1000},
	[7] = {7, "Legs", 1000},
	[8] = {8, "Feet", 1000},
	[9] = {16, "Main Hand", 1000},
	[10] = {17, "Off Hand", 1000},
	[11] = {18, "Ranged", 1000}
}

local function OnEvent()
	local total = 0
	local current, max

	for i = 1, 11 do
		if GetInventoryItemLink("player", slots[i][1]) ~= nil then
			current, max = GetInventoryItemDurability(slots[i][1])
			if current then
				slots[i][3] = current / max
				total = total + 1
			end
		end
	end
	table.sort(slots, function(a, b) return a[3] < b[3] end)

	if total > 0 then
		text:SetText(math.floor(slots[1][3] * 100) .. "% armor")
	else
		text:SetText("100% armor")
	end

	total = 0
end

function module:Initialize()
	module:RegisterEvent("UPDATE_INVENTORY_DURABILITY", OnEvent)
	module:RegisterEvent("MERCHANT_SHOW", OnEvent)
	module:RegisterEvent("PLAYER_ENTERING_WORLD", OnEvent)
end

E:RegisterModule(module:GetName())
