local vendorShowEvent = "MERCHANT_SHOW";
local frame = CreateFrame("FRAME");
frame:RegisterEvent(vendorShowEvent);

local function MerchantEventHandler(self, event, ...)
	SellTrash();
end

frame:SetScript("OnEvent", MerchantEventHandler);

function SellTrash()
    local totalValue = 0;
    for bag = 0, 4 do
       totalValue = totalValue + SellTrashInBag(bag);
    end
	
	if (totalValue > 0) then
		local formattedValue = GetFormattedTrashValue(totalValue);
		print("Sold trash items for : " .. formattedValue);
	end
end

function SellTrashInBag(bag)
    if GetContainerNumSlots(bag) == 0 then
		return 0;
	end
	
	local bagTrashValue = 0;
	for slot = 1, GetContainerNumSlots(bag) do
		local itemLink = GetContainerItemLink(bag, slot);
		if IsTrashItem(itemLink) then
			UseContainerItem(bag, slot);
			local itemValue = GetItemValue(itemLink);
			local count = GetItemStackCount(bag, slot);
			bagTrashValue = bagTrashValue + (itemValue * count);
		end
	end
	
	return bagTrashValue;
end

function IsTrashItem(item)
	return item and select(3, GetItemInfo(item)) == 0;
end

function GetItemValue(item)
	return select(11, GetItemInfo(item));
end

function GetItemStackCount(bag, slot)
	return select(2, GetContainerItemInfo(bag, slot));
end

function GetFormattedTrashValue(rawValue)
	local gold = math.floor(rawValue / 10000);
	local silver = math.floor((rawValue % 10000) / 100);
	local copper = (rawValue % 10000) % 100;
	
	return format(GOLD_AMOUNT_TEXTURE.." "..SILVER_AMOUNT_TEXTURE.." "..COPPER_AMOUNT_TEXTURE, gold, 0, 0, silver, 0, 0, copper, 0, 0);
end
