local SousChef = SousChef
local u = SousChef.Utility
local m = SousChef.Media
local LibSort = LibStub:GetLibrary("LibSort-1.0")

function SousChef.AddRankToSlot(row, funcs)
	local idFunc = funcs[1]
    local slot = row.dataEntry.data
    local bagId = slot[funcs[2]]
    local slotIndex = funcs[3] and slot[funcs[3]] or nil

	local rankIcon = SousChef.getIcon(row)

	-- Allow for ingeniousclown's Inventory Grid View
	if row:GetWidth() - row:GetHeight() < 5 then	-- if we're mostly square
		rankIcon:SetDimensions(20,20)
		rankIcon:ClearAnchors()
		rankIcon:SetAnchor(TOPLEFT, row, TOPLEFT, 2)
	else
		rankIcon:SetDimensions(30, 30)
		rankIcon:ClearAnchors()
		rankIcon:SetAnchor(RIGHT, row, RIGHT, -50)
	end

	rankIcon:SetHidden(true)

	-- Are we gold or soulgem slot? Stay hidden and go away
	if not bagId or not slot.name or slot.name == "" then return end

	local id = u.GetItemID(idFunc(bagId, slotIndex))
	local texture = SousChef.Pantry[id]
	if SousChef.settings.showAltIngredientKnowledge then texture = SousChef.settings.Pantry[id] end
	if texture then

		rankIcon:SetHidden(false)

		if SousChef.settings.boldIcon then
			rankIcon:SetTexture(m.COOKINGB[texture])
		else
			rankIcon:SetTexture(m.COOKING[texture])
		end

		if SousChef:IsOnShoppingList(id) then
			rankIcon:SetColor(SousChef.settings.shoppingColour[1], SousChef.settings.shoppingColour[2], SousChef.settings.shoppingColour[3])
		else
			if SousChef.settings.onlyShowShopping then return rankIcon:SetHidden(true) end
			rankIcon:SetColor(SousChef.settings.colour[1], SousChef.settings.colour[2], SousChef.settings.colour[3])
		end
		return
	end

    if SousChef.settings.processRecipes then
    	if u.MatchInIgnoreList(slot.name) then return end
    	if slot.name:find(GetString(SI_ITEMTYPE29)) then
	        local match = u.MatchInCookbook(slot.name)
	        local gmatch = u.MatchInGlobalCookbook(slot.name)
	        if (match and SousChef.settings.checkKnown == "known") or
	           (not match and SousChef.settings.checkKnown == "unknown")then
	            rankIcon:SetTexture(m.CANLEARN)
	            rankIcon:SetHidden(false)
	            if not match and gmatch and SousChef.settings.checkKnown == "unknown" and SousChef.settings.markAlt then
	                rankIcon:SetColor(1,1,1,0.2)
	            else
	                rankIcon:SetColor(1,1,1,1)
	            end
	        end
	    end
    end
end

function SousChef.UnregisterSort()
	LibSort:Unregister("Sous Chef")
end

function SousChef.SetupSort()
	LibSort:Register("Sous Chef", "Ingredient Rank", "The Provisioning Rank", "provisioningRank", SousChef.FindIngredientRank)
	LibSort:RegisterDefaultOrder("Sous Chef", {"Ingredient Rank"})
end

function SousChef.FindIngredientRank(slotType, bagId, slotIndex)
	local id = u.GetItemID(GetItemLink(bagId, slotIndex))
	local texture = SousChef.Pantry[id]
	if SousChef.settings.showAltIngredientKnowledge then texture = SousChef.settings.Pantry[id] end
	return texture or 100
end