local addOnName = ...
local _G = _G
local pairs = _G.pairs
local select = _G.select
local GetItemInfo = _G.GetItemInfo
local GetSpellInfo = _G.GetSpellInfo
local GetAddOnMetadata = _G.GetAddOnMetadata
local BII3 = _G[addOnName]
local indexTable = {
	["무기"] = 0,
	["Weapon"] = 0,
	["방어구"] = 1,
	["Armor"] = 1,
	["제조법"] = 2,
	["Recipe"] = 2,
	["가방"] = 3,
	["Container"] = 3,
	["재료"] = 4,
	["Reagent"] = 4,
	["직업용품"] = 4,
	["Trade Goods"] = 4,
	["소비용품"] = 5,
	["Consumable"] = 5,
	["보석"] = 6,
	["Gem"] = 6,
	["문양"] = 7,
	["Glyph"] = 7,
}
local name, rarity, mainType, list
local removeItem = "%s|1이;가; 즐겨찾기(%s)에서 삭제되었습니다."
local insertItem = "%s|1이;가; 즐겨찾기(%s)에 추가되었습니다."

local function refreshList(index, link, form)
	if BII3:CreateFavorite(index) then
		if BII3:IsVisible() then
			BII3:Update(true)
		else
			BII3.forceRefresh = true
		end
	end
	DEFAULT_CHAT_FRAME:AddMessage(form:format(link, select(2, BII3:GetCategoryName("A"..index.."0"))))
end

function BII3:IsFavorite(id)
	for index, items in pairs(self.chardb.favorite) do
		if items[id] then
			return index
		end
	end
	return nil
end

function BII3:AddFavorite(id)
	name = self:IsFavorite(id)
	if name then
		self.chardb.favorite[name][id] = nil
		refreshList(name, self:GetItemLink(id) or self:GetItemColorName(id), removeItem)
		self.itemNameDB[id] = nil
		name = nil
	elseif id > 0 then
		name, _, rarity, _, _, mainType = GetItemInfo(id)
		if name then
			self.chardb.favorite[indexTable[mainType] or 8][id] = true
			if not(self.itemNameDB[id] or GetAddOnMetadata(addOnName.."_UI", "X-DB-ItemName-"..id)) then
				self.itemNameDB[id] = rarity.."|"..name
			end
			refreshList(indexTable[mainType] or 9, self:GetItemLink(id) or self:GetItemColorName(id), insertItem)
		end
		name, rarity, mainType = nil
	elseif GetSpellInfo(-id) then
		name = self:GetItemLink(id)
		if name:find("enchant:") then
			self.chardb.favorite[2][id] = true
			refreshList(2, name, insertItem)
		elseif name then
			self.chardb.favorite[8][id] = true
			refreshList(8, name, insertItem)
		end
	end
end

function BII3:CreateFavorite(index)
	if self.itemList then
		list = nil
		for id in pairs(self.chardb.favorite[index]) do
			if list then
				list = list.."/"..id
			else
				list = id
			end
		end
		self.itemList["A"..index.."0"] = list and ("!"..list) or ""
		list = nil
		return true
	end
	return nil
end