BINDING_HEADER_BLINKTRASH = "블링크의 잡템 정리"
BINDING_NAME_BLINKTRASH_SELLTRASH = "잡템 팔기"

BLINKTRASH_DEBUG = false
BLINKTRASH_ITEMS = {}
BLINKTRASH_SELLCOUNT = 12 -- 한번에 판매할 갯수 : 0일경우 한꺼번에 다 팜

function BlinkTrash_Print(msg, r, g, b , frame)
	if ( not r ) then
		r = 1.0
	end
	if ( not g ) then
		g = 1.0
	end
	if ( not b ) then
		b = 0.0
	end
	if ( not msg or msg == nil ) then
		msg = "-nil-"
	end
	if( frame ) then
		frame:AddMessage(msg, r, g, b)
	else
		ChatFrame1:AddMessage(msg, r, g, b)
	end
end

function BlinkTrash_ItemIsLocked(bag, slot)
	if bag == -1 and slot == -1 then return false end

	if bag == -1 then
		return IsInventoryItemLocked(slot)
	else
		local _, _, retval = GetContainerItemInfo(bag, slot)
		return retval
	end
end

function BlinkTrash_ScanBag()
	BLINKTRASH_ITEMS = {}
	local maxslot = 0
	local emptyslot, freeSlots, bagFamily = 0
	for i=BACKPACK_CONTAINER, NUM_BAG_FRAMES do
		freeSlots, bagFamily = GetContainerNumFreeSlots(i)
		if ( bagFamily == 0 ) then
			emptyslot = emptyslot + freeSlots
			for j=1, GetContainerNumSlots(i) do
				local link = GetContainerItemLink(i, j)
				local name, rarity, id, stackCount, sellPrice 
				if ( link ) then
					name, _, rarity, _, _, _, _, _, _, _, sellPrice = GetItemInfo(link)
					_, stackCount = GetContainerItemInfo(i, j)
					id = BlinkTrash_LinkToID(link)
				end
				if ( name and rarity == 0 ) then -- is trash item
					table.insert( BLINKTRASH_ITEMS, {bag=i, slot=j, name=name, id=id, count=stackCount, price = sellPrice} )
				end
				maxslot = maxslot + 1
			end
		end
	end
	return emptyslot, maxslot
end

function BlinkTrash_LinkToID(link)
	if link then
		local _, _, id = string.find(link, "(%d+):")
		return id
	end
end

function BlinkTrash_SellTrashItems()
	local emptyslot, maxslot = BlinkTrash_ScanBag()
	local item_count = #BLINKTRASH_ITEMS
	local sold = 0
	if ( item_count > 0 and MerchantFrame:IsVisible() ) then
		if ( InCombatLockdown() ) then
			BlinkTrash_Print("전투중에는 아이템을 팔수 없습니다.")
			return
		end
		local items = BlinkTrash_PopItems()
		if ( items and type(items)=='table' ) then
			for idx, item in ipairs(items) do
				if ( BlinkTrash_ItemIsLocked(item.bag, item.slot) ) then
					-- do nothing
				else
					BlinkTrash_Print(string.format("%s|1을;를;", GetContainerItemLink(item.bag, item.slot)).." 상점에 팔았습니다.")
					UseContainerItem( item.bag, item.slot )
					sold = sold + 1
				end
			end
		end
		local remain = #BLINKTRASH_ITEMS
		BlinkTrash_Print(""..sold.. "개의 잡템을 팔고, ".. remain.. "개의 잡템이 남았습니다.")
	elseif ( item_count > 0 and not MerchantFrame:IsVisible() ) then
		BlinkTrash_Print("상점창이 열려있지 않으면 팔 수 없습니다. ("..item_count.."개)")
		local strPrice = BlinkTrash_GetPrice()
		if ( strPrice and strPrice~="" ) then
			BlinkTrash_Print("판매예상금액 ("..strPrice..")")
		end
	else
		BlinkTrash_Print("정리할 잡템이 없습니다.")
	end
	BlinkTrash_Print("가방 "..(maxslot-emptyslot).." / "..maxslot)
end

function BlinkTrash_PopItems()
	local result = {}
	if ( BLINKTRASH_SELLCOUNT > 0 ) then
		if ( #BLINKTRASH_ITEMS >= BLINKTRASH_SELLCOUNT ) then
			for i=1, BLINKTRASH_SELLCOUNT, 1 do
				local item = table.remove(BLINKTRASH_ITEMS, 1)
				table.insert(result, item)
			end
			return result
		elseif ( #BLINKTRASH_ITEMS > 0 ) then
			local count = #BLINKTRASH_ITEMS
			for i=1, count, 1 do
				local item = table.remove(BLINKTRASH_ITEMS, 1)
				table.insert(result, item)
			end
			return result
		else
			return nil
		end
	else
		return BLINKTRASH_ITEMS
	end
end

function BlinkTrash_GetPrice()
	local item_count = #BLINKTRASH_ITEMS
	local totalprice = 0
	local uncounted = 0
	local strPrice
	local id = 0
	local price = 0

	for k, item in pairs(BLINKTRASH_ITEMS) do
		price = tonumber(item.price)
		if (price and price > 0) then
			totalprice = totalprice + ( price * item.count )
		else
			uncounted = uncounted + 1
		end
	end

	local gold, silver, copper = BlinkTrash_GoldFormat(totalprice)

	if gold > 0 then
		strPrice = "|cffffdd00"..gold.." 골드|r"
	end
	if silver > 0 then
		strPrice = (strPrice and strPrice .. " " or "") .. "|cffdddddd"..silver.." 실버|r"
	end
	if copper > 0 then
		strPrice = (strPrice and strPrice .. " " or "") .. "|cffff8800"..copper.." 쿠퍼|r"
	end
	if (totalprice>0 and uncounted>0) then
		strPrice = strPrice .. " |cff00dd00이상|r"
	elseif ( totalprice == 0 and uncounted>0 ) then
		strPrice = strPrice .. "|cff9d9d9d알수없음|r"
	end
	return strPrice
end

function BlinkTrash_GoldFormat(money)
	local gold = floor(money / (COPPER_PER_SILVER * SILVER_PER_GOLD))
	local silver = floor((money - (gold * COPPER_PER_SILVER * SILVER_PER_GOLD)) / COPPER_PER_SILVER)
	local copper = money % COPPER_PER_SILVER
	return gold, silver, copper
end

function BlinkTrash_Repair()
	if CanMerchantRepair() then
		local strPrice, cost = nil, GetRepairAllCost()

		if cost > 0 then
			local gold, silver, copper = BlinkTrash_GoldFormat(cost)
			if gold > 0 then
				strPrice = "|cffffdd00"..gold.." 골드|r"
			end
			if silver > 0 then
				strPrice = (strPrice and strPrice .. " " or "") .. "|cffdddddd"..silver.." 실버|r"
			end
			if copper > 0 then
				strPrice = (strPrice and strPrice .. " " or "") .. "|cffff8800"..copper.." 쿠퍼|r"
			end

			if cost < GetMoney() * 0.3 then
				RepairAllItems()
				PlaySound("ITEM_REPAIR")
				BlinkTrash_Print("장비를 수리했습니다. (" .. strPrice .. " 사용)")
			else
				BlinkTrash_Print("|cffff3333수리비용이 소지금의 30%를 넘어 수리하지 않았습니다.|r (수리비용 " .. strPrice .. ")")
			end
		end
	end
end

--[[ 이 주석을 풀면 상점오픈시 자동으로 잡템을 팔고 장비를 수리합니다.
local frame = CreateFrame("Frame", "bTrashFrame")
frame:RegisterEvent("MERCHANT_SHOW")
frame:SetScript("OnEvent", function ()
	-- 상점열리면 자동팔기
	BlinkTrash_SellTrashItems()

	-- 상점열리면 자동 수리
	BlinkTrash_Repair()
end)
]]
