local _G = _G
local type = _G.type
local pairs = _G.pairs
local tinsert = _G.table.insert
local GetItemInfo = _G.GetItemInfo

local LIS = LibStub("LibItemSpec-2.0")
local LIC = LibStub("LibItemCheck-1.0")

local itemLoc, statText, splitText, itemRarity, itemLevel, itemType

local tradeSkillCode = { "연금술", "대장기술", "마법부여", "기계공학", "약초채집", "보석세공", "가죽세공", "재봉술" }
local tradeSkillOnlyItems = InvenSimulatorUI.database.tradeSkillOnlyItems

function InvenSimulatorUI:IsTradeSkillOnly(id)
	id = type(id) == "string" and LIS:GetItemID(id) or id
	if type(id) == "number" and tradeSkillOnlyItems[id] then
		return tradeSkillCode[tradeSkillOnlyItems[id] ]
	end
	return nil
end

InvenSimulatorUI.itemDB = {}
InvenSimulatorUI.itemDataByLoc = {}
InvenSimulatorUI.itemDataByStat = {}
InvenSimulatorUI.equipLocSlots = {
	["INVTYPE_HEAD"] = 1,
	["INVTYPE_NECK"] = 2,
	["INVTYPE_SHOULDER"] = 3,
	["INVTYPE_BODY"] = 4,
	["INVTYPE_CHEST"] = 5,
	["INVTYPE_ROBE"] = 5,
	["INVTYPE_WAIST"] = 6,
	["INVTYPE_LEGS"] = 7,
	["INVTYPE_FEET"] = 8,
	["INVTYPE_WRIST"] = 9,
	["INVTYPE_HAND"] = 10,
	["INVTYPE_FINGER"] = { 11, 12 },
	["INVTYPE_TRINKET"] = { 13, 14 },
	["INVTYPE_CLOAK"] = 15,
	["INVTYPE_2HWEAPON"] = { 16, 17 },
	["INVTYPE_WEAPON"] = { 16, 17 },
	["INVTYPE_WEAPONMAINHAND"] = 16,
	["INVTYPE_WEAPONOFFHAND"] = 17,
	["INVTYPE_HOLDABLE"] = 17,
	["INVTYPE_SHIELD"] = 17,
	["INVTYPE_RANGED"] = 18,
	["INVTYPE_RANGEDRIGHT"] = 18,
	["INVTYPE_THROWN"] = 18,
	["INVTYPE_RELIC"] = 18,
	["INVTYPE_TABARD"] = 19,
}

function InvenSimulatorUI:ScanItemCache()
	if self.hasItemData then return end
	self.hasItemData = true
	for i = 1, self.maxItemIds do
		itemRarity, itemLevel, _, _, _, _, itemLoc = select(3, GetItemInfo(i))
		if itemRarity and (itemRarity > 2 and itemLevel > 180) or itemLoc == "INVTYPE_BODY" or itemLoc == "INVTYPE_TABARD" then
			itemLoc, statText = LIC:IsUsableItem(i)
			if itemLoc then
				self.itemDataByLoc[itemLoc] = self.itemDataByLoc[itemLoc] or {}
				if not self.itemDataByLoc[itemLoc][i] then
					self.itemDataByLoc[itemLoc][i] = true
					if statText then
						splitText = { ("|"):split(statText) }
						for _, v in pairs(splitText) do
							self.itemDataByStat[v] = self.itemDataByStat[v] or {}
							self.itemDataByStat[v][i] = true
						end
					end
					if type(self.equipLocSlots[itemLoc]) == "table" then
						for _, slot in pairs(self.equipLocSlots[itemLoc]) do
							self.itemDB[slot] = self.itemDB[slot] or {}
							tinsert(self.itemDB[slot], i)
						end
					elseif type(self.equipLocSlots[itemLoc]) == "number" then
						self.itemDB[self.equipLocSlots[itemLoc]] = self.itemDB[self.equipLocSlots[itemLoc]] or {}
						tinsert(self.itemDB[self.equipLocSlots[itemLoc]], i)
					end
				end
			end
		end
	end
end