local _G = getfenv(0);

local f = InfoPanel_AddPlugin();
local RepairInfo = {};
--local lastUpdate = 0;
local ItemSlots = {
	"HeadSlot",
	"NeckSlot",
	"ShoulderSlot",
	"BackSlot",
	"ChestSlot",
	"ShirtSlot",
	"TabardSlot",
	"WristSlot",
	"HandsSlot",
	"WaistSlot",
	"LegsSlot",
	"FeetSlot",
	"Finger0Slot",
	"Finger1Slot",
	"Trinket0Slot",
	"Trinket1Slot",
	"MainHandSlot",
	"SecondaryHandSlot",
	"RangedSlot",
};

for _, slotName in ipairs(ItemSlots) do
	RepairInfo[slotName] = {};
end

--------------------------------------------------------------------------------------------------------
--                                             Functions                                              --
--------------------------------------------------------------------------------------------------------

-- OnEvent
local function OnEvent(self,event)
	-- Az: Need a better way to throttle the scanning here, so it doesn't scan multiple times in a row,
	-- the current throttle allows the first scan to pass, but trailing events to get throttled,
	-- but it is the later events which provide the most information.

	if (event == "UNIT_INVENTORY_CHANGED" and arg1 ~= "player") then
		return;
	end
	-- Ignore Event Spams (Logins etc) and Inventory Changes of other units
--	if (GetTime() < lastUpdate) then
--		AzMsg("|2Ignored!|r - "..event);
--		return;
--	end
--	lastUpdate = (GetTime() + 1);
	-- Equip
	RepairInfo.equipCost = 0;
	RepairInfo.minDur = 100;
	for _, slotName in ipairs(ItemSlots) do
		RepairInfo[slotName].cost = select(3,IPWorkTip:SetInventoryItem("player",GetInventorySlotInfo(slotName))) or 0;
		RepairInfo[slotName].min, RepairInfo[slotName].max = GetInventoryItemDurability(GetInventorySlotInfo(slotName));
		if (RepairInfo[slotName].cost > 0) then
			RepairInfo.equipCost = (RepairInfo.equipCost + RepairInfo[slotName].cost);
			RepairInfo.minDur = min(RepairInfo.minDur,RepairInfo[slotName].min / RepairInfo[slotName].max * 100);
		end
	end
	-- Bags
	local repairCost;
	RepairInfo.bagCost = 0;
	for bag = 0, NUM_BAG_FRAMES do
		for slot = 1, GetContainerNumSlots(bag) do
			repairCost = select(2,IPWorkTip:SetBagItem(bag,slot)) or 0;
			if (repairCost > 0) then
				RepairInfo.bagCost = (RepairInfo.bagCost + repairCost);
			end
		end
	end
	-- Set Label
	InfoPanel_SetText(f,"%d%%",RepairInfo.minDur);
	InfoPanel_SetTextColor(f,RepairInfo.minDur,20,60);
end

-- Mouse OnEnter
local function OnEnter(self)
	InfoPanel_MakeTip(f,"내구도 정보");

	for _, slotName in ipairs(ItemSlots) do
		if (RepairInfo[slotName].cost > 0) then
			--GameTooltip:AddDoubleLine(format("|cff00ff00%d / %d|r %s",RepairInfo[slotName].min,RepairInfo[slotName].max,_G[slotName:upper()]),InfoPanel_FormatCopper(RepairInfo[slotName].cost));
			GameTooltip:AddDoubleLine(format("|cff00ff00%d%%|r %s",RepairInfo[slotName].min / RepairInfo[slotName].max * 100,_G[slotName:upper()]),InfoPanel_FormatCopper(RepairInfo[slotName].cost));
		end
	end
	if (GameTooltip:NumLines() > 1) then
		GameTooltip:AddLine(" ");
	end

	local costTotal = (RepairInfo.equipCost + RepairInfo.bagCost);
	if (costTotal > 0) then
		if (RepairInfo.bagCost > 0) then
			GameTooltip:AddDoubleLine("가방내 장비",InfoPanel_FormatCopper(RepairInfo.bagCost));
			GameTooltip:AddLine(" ");
		end
		GameTooltip:AddDoubleLine("수리비",InfoPanel_FormatCopper(costTotal));
		GameTooltip:AddDoubleLine("평판:우호적이상",InfoPanel_FormatCopper(floor(costTotal*0.9)));
	else
		GameTooltip:AddLine("손상없음");
	end

	GameTooltip:Show();
end

-- OnClick
local function OnClick()
	if (ChatFrameEditBox:IsShown()) then
		local costTotal = (RepairInfo.equipCost + RepairInfo.bagCost);
		local fmtNormal = InfoPanel_FormatCopper(costTotal):gsub("|c%x%x%x%x%x%x%x%x",""):gsub("|r","");
		local fmtHonored = InfoPanel_FormatCopper(costTotal * 0.9):gsub("|c%x%x%x%x%x%x%x%x",""):gsub("|r","");
		ChatFrameEditBox:Insert(fmtNormal.." (Honored: "..fmtHonored..")");
	else
		OnEvent();
	end
end

--------------------------------------------------------------------------------------------------------
--                                              Finalize                                              --
--------------------------------------------------------------------------------------------------------

f.icon:SetTexture("Interface\\Icons\\Trade_BlackSmithing");
f:SetScript("OnEnter",OnEnter);
f:SetScript("OnEvent",OnEvent);
f:SetScript("OnClick",OnClick);
f:RegisterEvent("PLAYER_LOGIN");
f:RegisterEvent("PLAYER_REGEN_ENABLED");
f:RegisterEvent("UNIT_INVENTORY_CHANGED");
f:RegisterEvent("UPDATE_INVENTORY_ALERTS");
f:RegisterEvent("PLAYER_DEAD");
f:RegisterEvent("MERCHANT_CLOSED");

f:RegisterEvent("PLAYER_ALIVE");
f:RegisterEvent("PLAYER_UNGHOST");