local _G = _G
local pairs = _G.pairs
local ipairs = _G.ipairs
local select = _G.select
local tonumber = _G.tonumber
local tinsert = _G.table.insert
local GetItemIcon = _G.GetItemIcon
local GetItemInfo = _G.GetItemInfo
local GetSpellInfo = _G.GetSpellInfo

local LIS = LibStub("LibItemSpec-2.0")
local LDM = LibStub("LibDropMenu-2.0")

local gemSocketName = { ["M"] = "얼개 보석 홈", ["R"] = "붉은색 보석 홈", ["Y"] = "노란색 보석 홈", ["B"] = "푸른색 보석 홈", ["N"] = "다색 보석 홈" }
local gem, gemInfo, gemNum, itemType1, itemType2, enchantNum, enchantCode, openedSlot, openedSocket, openedCode
local pf = strsub(UnitFactionGroup("player"), 1, 1) == "H"

local draonEyeFunc = function()
	if InvenSimulatorUI:HasTradeSkill("보석세공") then
		if InvenSimulatorUI.database.dragonEyeGem[openedCode] then
			return nil
		elseif InvenSimulatorUI.numDragonEyeGem >= 3 then
			return true
		else
			return nil
		end
	else
		return true
	end
end

local uniqueGemFunc = function(gemID)
	if openedCode == gemID then
		return nil
	elseif InvenSimulatorUI:GetGemIDCount(gemID) >= 1 then
		return true
	else
		return nil
	end
end

local function gemFunc(code)
	if openedSocket == 1 then
		InvenSimulatorUI:SetItem(openedSlot, InvenSimulatorUI:SetGemAndEnchant(InvenSimulatorUI.db.items[openedSlot], nil, code or 0), nil, true)
	elseif openedSocket == 2 then
		InvenSimulatorUI:SetItem(openedSlot, InvenSimulatorUI:SetGemAndEnchant(InvenSimulatorUI.db.items[openedSlot], nil, nil, code or 0), nil, true)
	elseif openedSocket == 3 then
		InvenSimulatorUI:SetItem(openedSlot, InvenSimulatorUI:SetGemAndEnchant(InvenSimulatorUI.db.items[openedSlot], nil, nil, nil, code or 0), nil, true)
	elseif openedSocket == 4 then
		InvenSimulatorUI:SetItem(openedSlot, InvenSimulatorUI:SetGemAndEnchant(InvenSimulatorUI.db.items[openedSlot], nil, nil, nil, nil, code or 0), nil, true)
	end
	LDM:CloseMenu(1)
end

local gemMenu = {
	type = "group", args = {
		red = { type = "group", order = 10, name = "붉은색 보석", desc = "붉은색 보석을 장착합니다.", args = {} },
		yellow = { type = "group", order = 20, name = "노란색 보석", desc = "노란색 보석을 장착합니다.", args = {} },
		blue = { type = "group", order = 30, name = "푸른색 보석", desc = "푸른색 보석을 장착합니다.", args = {} },
		orange = { type = "group", order = 40, name = "주황색(붉은+노란) 보석", desc = "주황색(붉은+노란) 보석을 장착합니다.", args = {} },
		purple = { type = "group", order = 50, name = "보라색(붉은+푸른) 보석", desc = "보라색(붉은+푸른) 보석을 장착합니다.", args = {} },
		green = { type = "group", order = 60, name = "녹색(노란+푸른) 보석", desc = "녹색(노란+푸른) 보석을 장착합니다.", args = {} },
		prismatic = { type = "group", order = 70, name = "다색(붉은+노란+푸른)", desc = "다색(붉은+노란+푸른) 보석을 장착합니다.", args = {} },
		del = { type = "execute", order = 100, name = "보석 제거", desc = "현재 아이템에서 보석을 제거합니다.", func = gemFunc },
	},
}

local metaGemMenu = { type = "group", args = {} }
local enchantMenu = { type = "group", args = {} }
local arrowMenu = { type = "group", args = {} }
local bulletMenu = { type = "group", args = {} }
local gemHasFunc = { [49110] = uniqueGemFunc, [42702] = uniqueGemFunc, [42701] = uniqueGemFunc, [36766] = draonEyeFunc, [42142] = draonEyeFunc, [42143] = draonEyeFunc, [42144] = draonEyeFunc, [42151] = draonEyeFunc, [42152] = draonEyeFunc, [42153] = draonEyeFunc, [42154] = draonEyeFunc, [42148] = draonEyeFunc, [42149] = draonEyeFunc, [42150] = draonEyeFunc, [42156] = draonEyeFunc, [42157] = draonEyeFunc, [42158] = draonEyeFunc, [36767] = draonEyeFunc, [42145] = draonEyeFunc, [42146] = draonEyeFunc, [42155] = draonEyeFunc }
local enchantDB = InvenSimulatorUI.database.enchantDB
local arrows = InvenSimulatorUI.database.arrowDPS
local bullets = InvenSimulatorUI.database.bulletDPS
local arrowList, bulletList

local function checkValue(v)
	if type(v) == "function" then
		if v() then
			return true
		end
	elseif v then
		return true
	end
	return nil
end

local function enchantFunc(code)
	LDM:CloseMenu(1)
	if code then
		InvenSimulatorUI:SetItem(openedSlot, InvenSimulatorUI:SetGemAndEnchant(InvenSimulatorUI.db.items[openedSlot], code), nil, true)
	else
		InvenSimulatorUI:SetItem(openedSlot, InvenSimulatorUI:SetGemAndEnchant(InvenSimulatorUI.db.items[openedSlot], 0), nil, true)
	end
	if openedSlot == 16 or openedSlot == 17 or openedSlot == 1 then
		InvenSimulatorUI:ModelUpdate()
	end
end

local function createEnchant(code)
	enchantNum = enchantNum + 1
	enchantMenu.args[enchantNum] = enchantMenu.args[enchantNum] or { type = "execute", order = enchantNum, func = enchantFunc }
	enchantMenu.args[enchantNum].hidden = nil
	if code then
		enchantMenu.args[enchantNum].name, enchantMenu.args[enchantNum].icon, enchantMenu.args[enchantNum].link, enchantMenu.args[enchantNum].arg1 = InvenSimulatorUI:GetEnchantmentName(code)
	else
		enchantMenu.args[enchantNum].name = "없음"
		enchantMenu.args[enchantNum].icon = nil
		enchantMenu.args[enchantNum].link = nil
		enchantMenu.args[enchantNum].desc = "해당 아이템의 강화 효과를 제거합니다."
		enchantMenu.args[enchantNum].arg1 = nil
	end
end

local function ammoFunc(code)
	LDM:CloseMenu(1)
	InvenSimulatorUI.db.ammo = code
	InvenSimulatorUI.ammoSlot.icon:SetTexture(InvenSimulatorUI.db.ammo and GetItemIcon(InvenSimulatorUI.db.ammo) or InvenSimulatorUI.ammoSlot.backgroundTextureName)
	InvenSimulatorUI:ScanItem()
	InvenSimulatorUI:UpdateStatList("left")
	InvenSimulatorUI:UpdateStatList("right")
end

local vc1, vc2

local function createGemMenu()
	local metaGemOrder = {}
	for gemType, gemTable in pairs(InvenSimulatorUI.database.gemDB) do
		if gemType == "meta" then
			for i, gem in ipairs(gemTable) do
				metaGemMenu.args[i] = { type = "execute", order = i, func = gemFunc }
				metaGemMenu.args[i].name, metaGemMenu.args[i].icon, metaGemMenu.args[i].link, metaGemMenu.args[i].arg1 = InvenSimulatorUI:GetEnchantmentName(gem)
				tinsert(metaGemOrder, i)
			end
		else
			for i, gem in ipairs(gemTable) do
				gemMenu.args[gemType].args[i] = { type = "execute", order = i, func = gemFunc }
				gemMenu.args[gemType].args[i].name, gemMenu.args[gemType].args[i].icon, gemMenu.args[gemType].args[i].link, gemMenu.args[gemType].args[i].arg1 = InvenSimulatorUI:GetEnchantmentName(gem)
				gemMenu.args[gemType].args[i].hidden = gemHasFunc[gem]
			end
		end
	end
	sort(metaGemOrder, function(a, b)
		return metaGemMenu.args[a].name < metaGemMenu.args[b].name
	end)
	for p, v in ipairs(metaGemOrder) do
		metaGemMenu.args[v].order = p
	end
	metaGemMenu.args.del = gemMenu.args.del
	gemMenu.args.prismatic.hidden = function()
		for _, v in pairs(gemMenu.args.prismatic.args) do
			if type(v.hidden) == "function" and v.arg1 then
				if not v.hidden(v.arg1) then
					return nil
				end
			elseif not checkValue(v.hidden) then
				return nil
			end
		end
		return true
	end
	LDM:RegisterMenu("InvenSimulatorMetaGemMenu", metaGemMenu)
	LDM:RegisterMenu("InvenSimulatorGemMenu", gemMenu)
end

function InvenSimulatorUI:OpenGemMenu(parent)
	if not LDM.menus["InvenSimulatorMetaGemMenu"] then
		createGemMenu()
	end
	if parent.buttonType == "metagem" then
		if LDM:IsOpen("InvenSimulatorMetaGemMenu") then
			LDM:CloseMenu(1)
		else
			openedSlot = InvenSimulatorItemEnchantingFrame.openSlot
			openedSocket = parent:GetID()
			openedCode = parent.code or 0
			metaGemMenu.name = parent.tooltip
			metaGemMenu.icon = parent.tooltipIcon
			LDM:OpenMenu("InvenSimulatorMetaGemMenu", "TOPLEFT", parent, "TOPRIGHT", 0, 0)
		end
	elseif parent.buttonType == "gem" then
		if LDM:IsOpen("InvenSimulatorGemMenu") then
			LDM:CloseMenu(1)
		else
			openedSlot = InvenSimulatorItemEnchantingFrame.openSlot
			openedSocket = parent:GetID()
			openedCode = parent.code or 0
			gemMenu.name = parent.tooltip
			gemMenu.icon = parent.tooltipIcon
			LDM:OpenMenu("InvenSimulatorGemMenu", "TOPLEFT", parent, "TOPRIGHT", 0, 0)
		end
	else
		LDM:CloseMenu(1)
	end
end

function InvenSimulatorUI:OpenEnchantMenu(parent)
	openedSlot = InvenSimulatorItemEnchantingFrame.openSlot
	openedSocket = parent:GetID()
	openedCode = parent.code or 0
	if LDM:IsOpen("InvenSimulatorEnchantMenu") then
		LDM:CloseMenu(1)
	else
		openedSlot = InvenSimulatorItemEnchantingFrame.openSlot
		enchantMenu.opendSlot = openedSlot
		enchantMenu.name = (self.class == "죽음의 기사" and (openedSlot == 16 or openedSlot == 17)) and "룬벼리기" or "마법부여"
		enchantNum = 0
		itemType1, _, itemType2 = select(7, GetItemInfo(self.db.items[openedSlot]))
		for i = 1, 3 do
			if i == 3 then
				enchantCode = itemType2
			else
				enchantCode = itemType2.."_"..(self.db.tradeSkill[i] or "")
			end
			if enchantDB[enchantCode] then
				if enchantDB[enchantCode][itemType1] then
					for _, code in ipairs(enchantDB[enchantCode][itemType1]) do
						createEnchant(code, openedSlot)
					end
				end
				if enchantDB[enchantCode]["*"] then
					for _, code in ipairs(enchantDB[enchantCode]["*"]) do
						createEnchant(code, openedSlot)
					end
				end
			elseif enchantDB[enchantCode.."!"] then
				enchantCode = enchantCode.."!"
				if enchantDB[enchantCode][itemType1] then
					for _, code in ipairs(enchantDB[enchantCode][itemType1]) do
						createEnchant(code, openedSlot)
					end
				end
				if enchantDB[enchantCode]["*"] then
					for _, code in ipairs(enchantDB[enchantCode]["*"]) do
						createEnchant(code, openedSlot)
					end
				end
				break
			end
		end
		createEnchant(nil, openedSlot)
		for i = enchantNum + 1, #enchantMenu.args do
			enchantMenu.args[i].hidden = true
		end
		LDM:RegisterMenu("InvenSimulatorEnchantMenu", enchantMenu)
		LDM:OpenMenu("InvenSimulatorEnchantMenu", "TOPLEFT", parent, "TOPRIGHT", 0, 0)
	end
end

local function mainMenuHidden(slot)
	return not InvenSimulatorUI.db.items[slot]
end

local mainMenu = {
	type = "group",
	args = {
		enchant = {
			type = "execute", name = "아이템 강화", desc = "아이템에 마법부여나 보석을 장착합니다.", order = 10,
			func = function(slot)
				InvenSimulatorUI:OpenItemEnchantingFrame(slot)
				LDM:CloseMenu(1)
			end,
			hidden = function(slot) return not(InvenSimulatorUI.db.items[slot] and (InvenSimulatorUI:GetNumSocket(InvenSimulatorUI.db.items[slot]) > 0 or InvenSimulatorUI:IsEnchantable(InvenSimulatorUI.db.items[slot]))) end,
		},
		clearEnchant = {
			type = "execute", name = "모든 강화 효과 제거", desc = "아이템에 있는 마법부여 및 보석 효과를 제거합니다.", order = 20,
			func = function(slot)
				InvenSimulatorUI:SetItem(slot, InvenSimulatorUI:SetGemAndEnchant(InvenSimulatorUI.db.items[slot], 0, 0, 0, 0, 0), nil, true)
			end,
			hidden = function(slot) return not(InvenSimulatorUI.db.items[slot] and (InvenSimulatorUI:GetNumSocket(InvenSimulatorUI.db.items[slot]) > 0 or InvenSimulatorUI:IsEnchantable(InvenSimulatorUI.db.items[slot]))) end,
		},
		search = {
			type = "execute", name = "아이템 찾기", desc = "착용할 아이템을 검색합니다.", order = 30,
			func = function(slot)
				InvenSimulatorUI:OpenItemList(slot)
				LDM:CloseMenu(1)
			end,
		},
		clearItem = {
			type = "execute", name = "아이템 착용 해제", desc = "현재 아이템을 착용 해제합니다.", order = 40,
			func = function(slot)
				InvenSimulatorUI:SetItem(slot, nil, nil, true)
				InvenSimulatorUI:ModelUpdate()
				LDM:CloseMenu(1)
			end,
			hidden = mainMenuHidden,
		},
		getMyItem = {
			type = "execute", name = "현재 착용 중인 장비 가져오기", desc = "현재 착용중인 아이템을 가져옵니다.", order = 45,
			func = function(slot)
				local link = GetInventoryItemLink("player", slot)
				if link then
					InvenSimulatorUI:SetItem(slot, link, nil, true)
					InvenSimulatorUI:ModelUpdate()
				end
				LDM:CloseMenu(1)
			end,
			hidden = function(slot)
				return not GetInventoryItemLink("player", slot)
			end,
		},
		saveItem = {
			type = "execute", name = "아이템 저장소에 저장하기", desc = "현재 아이템을 아이템 저장소에 저장합니다.", order = 46,
			func = function(slot)
				InvenSimulatorSaveItemFrame:SaveItem(InvenSimulatorUI.db.items[slot], true)
				LDM:CloseMenu(1)
			end,
			hidden = mainMenuHidden,
		},
		linkItem = {
			type = "execute", name = "채팅창에 링크", desc = "아이템을 채팅창에 링크합니다.", order = 50,
			func = function(slot)
				if TinyPad and TinyPadEditBox and TinyPadEditBox:IsShown() and TinyPad.has_focus then
					TinyPadEditBox:Insert(InvenSimulatorUI.db.items[slot])
				else
					ChatFrame1EditBox:Show()
					ChatFrame1EditBox:Insert(InvenSimulatorUI.db.items[slot])
				end
				LDM:CloseMenu(1)
			end,
			hidden = mainMenuHidden,
		},
		refTooltip = {
			type = "execute", name = "툴팁 띄우기", desc = "아이템을 툴팁으로 띄웁니다.", order = 60,
			func = function(slot)
				ShowUIPanel(ItemRefTooltip)
				if not ItemRefTooltip:IsShown() then
					ItemRefTooltip:SetOwner(UIParent, "ANCHOR_PRESERVE")
				end
				ItemRefTooltip:SetHyperlink(InvenSimulatorUI.db.items[slot])
				LDM:CloseMenu(1)
			end,
			hidden = mainMenuHidden,
		},
	},
}
LDM:RegisterMenu("InvenSimulatorItemMenu", mainMenu)

function InvenSimulatorUI:OpenMenu(parent)
	if LDM:IsOpen("InvenSimulatorItemMenu") then
		LDM:CloseMenu(1)
	else
		if self.db.items[parent:GetID()] then
			mainMenu.name = InvenSimulatorUI:GetSlotItemName(parent:GetID())
			mainMenu.icon = GetItemIcon(self.db.items[parent:GetID()])
		else
			mainMenu.name = parent.tooltipText
			mainMenu.icon = parent.backgroundTextureName
		end
		for p in pairs(mainMenu.args) do
			mainMenu.args[p].arg1 = parent:GetID()
		end
		LDM:OpenMenu("InvenSimulatorItemMenu", "TOPLEFT", parent, "TOPRIGHT", 0, 0)
	end
end

function InvenSimulatorUI:IsEnchantable(link)
	local itemType1, _, itemType2 = select(7, GetItemInfo(link))
	if itemType1 and itemType2 then
		if enchantDB[itemType2] and (enchantDB[itemType2]["*"] or enchantDB[itemType2][itemType1]) then
			return true
		else
			local enchantCode = itemType2.."_"..(self.db.tradeSkill[1] or "").."!"
			if enchantDB[enchantCode] and (enchantDB[enchantCode]["*"] or enchantDB[itemType2][enchantCode]) then
				return true
			end
			enchantCode = itemType2.."_"..(self.db.tradeSkill[1] or "")
			if enchantDB[enchantCode] and (enchantDB[enchantCode]["*"] or enchantDB[itemType2][enchantCode]) then
				return true
			end
			enchantCode = itemType2.."_"..(self.db.tradeSkill[2] or "").."!"
			if enchantDB[enchantCode] and (enchantDB[enchantCode]["*"] or enchantDB[itemType2][enchantCode]) then
				return true
			end
			enchantCode = itemType2.."_"..(self.db.tradeSkill[2] or "")
			if enchantDB[enchantCode] and (enchantDB[enchantCode]["*"] or enchantDB[itemType2][enchantCode]) then
				return true
			end
		end
	end
	return nil
end

local gemIds, numGems, gemText = {}

function InvenSimulatorUI:GetNumSocket(link)
	gemText = LIS:GetItemGemInfo(link) or ""
	numGems = gemText:len()
	gemIds[1], gemIds[2], gemIds[3] = self:GetGemID(link)
	if numGems < 3 and gemIds[numGems + 1] > 0 then
		gemText = gemText.."N"
		numGems = numGems + 1
	end
	return numGems, gemText, gemIds[1], gemIds[2], gemIds[3]
end

local tradeSkillMenu
local tradeSkillTooltip = { ["연금술"] = 51304, ["재봉술"] = 51309, ["가죽세공"] = 51302, ["대장기술"] = 51300, ["기계공학"] = 51306, ["마법부여"] = 51313, ["보석세공"] = 51311, ["주문각인"] = 45363, ["채광"] = 53040, ["무두질"] = 53666, ["약초채집"] = 55503 }


function InvenSimulatorUI:OpenTradeSkillMenu(button)
	if tradeSkillMenu == nil then
		tradeSkillMenu = { type = "group", name = "전문기술", args = {} }
		local function tradeSkillFunc(id, skill)
			LDM:CloseMenu(1)
			InvenSimulatorUI["tradeSkillButton"..id]:SetText(skill)
			InvenSimulatorUI:ChangeTradeSkill(id, skill)
		end
		for id, name in ipairs(self.tradeSkillList) do
			tradeSkillMenu.args[id] = { type = "execute", order = id, name = name, arg2 = name, func = tradeSkillFunc, link = "spell:"..(tradeSkillTooltip[name]) }
		end
		LDM:RegisterMenu("InvenSimulatorTradeSkillMenu", tradeSkillMenu)
	end
	if LDM:IsOpen("InvenSimulatorTradeSkillMenu") then
		LDM:CloseMenu(1)
	else
		for i = 1, #tradeSkillMenu.args do
			tradeSkillMenu.args[i].arg1 = button:GetID()
			if tradeSkillMenu.args[i].name == self.db.tradeSkill[button:GetID()] then
				tradeSkillMenu.args[i].icon = "Interface\\Buttons\\UI-CheckBox-Check"
			else
				tradeSkillMenu.args[i].icon = nil
			end
		end
		LDM:OpenMenu("InvenSimulatorTradeSkillMenu", "TOPLEFT", button, "TOPRIGHT", 0, 0)
	end
end

function InvenSimulatorUI:TransmuteAmmo()
	if self.db.items[18] then
		if self.db.ammo and (arrows[self.db.ammo] or bullets[self.db.ammo]) then
			if select(7, GetItemInfo(self.db.items[18])) == "총기류" then
				if arrows[self.db.ammo] then
					local dpsGap, sid = arrows[self.db.ammo]
					for id, dps in pairs(bullets) do
						if dps == arrows[self.db.ammo] then
							self.db.ammo = id
							return
						elseif dpsGap > abs(arrows[self.db.ammo] - dps) then
							dpsGap = abs(arrows[self.db.ammo] - dps)
							sid = id
						end
					end
					self.db.ammo = sid
				else
					return
				end
			elseif bullets[self.db.ammo] then
				local dpsGap, sid = bullets[self.db.ammo]
				for id, dps in pairs(arrows) do
					if dps == bullets[self.db.ammo] then
						self.db.ammo = id
						return
					elseif dpsGap > abs(bullets[self.db.ammo] - dps) then
						dpsGap = abs(bullets[self.db.ammo] - dps)
						sid = id
					end
				end
				self.db.ammo = sid
			else
				return
			end
		end
		self.db.ammo = nil
	end
end

function InvenSimulatorUI:GetAmmoDPS()
	if self.db.items[18] then
		local rangedType = select(7, GetItemInfo(self.db.items[18]))
		if (rangedType == "활류" or rangedType == "총기류" or rangedType == "석궁류") and LIS:GetItemID(self.db.items[18]) ~= 34334 then
			return arrows[self.db.ammo] or bullets[self.db.ammo] or 0
		end
	end
	return 0
end

function InvenSimulatorUI:OpenAmmoMenu()
	if select(7, GetItemInfo(self.db.items[18])) == "총기류" then
		if not bulletList then
			bulletList = {}
			for id in pairs(bullets) do
				tinsert(bulletList, id)
			end
			sort(bulletList, function(a, b)
				if bullets[a] == bullets[b] then
					return a > b
				else
					return bullets[a] > bullets[b]
				end
			end)
			for i, id in ipairs(bulletList) do
				bulletMenu.args[i] = { type = "execute", order = i, arg1 = id, func = ammoFunc }
				bulletMenu.args[i].name, bulletMenu.args[i].icon, bulletMenu.args[i].link = self:GetEnchantmentName(id)
			end
			bulletMenu.args[#bulletMenu.args + 1] = { type = "execute", order = #bulletMenu.args + 1, arg1 = nil, func = ammoFunc, name = "탄환 제거", desc = "탄환을 제거합니다." }
			LDM:RegisterMenu("InvenSimulatorBulletMenu", bulletMenu)
		end
		if LDM:IsOpen("InvenSimulatorBulletMenu") then
			LDM:CloseMenu(1)
		else
			LDM:OpenMenu("InvenSimulatorBulletMenu", "TOPLEFT", self.ammoSlot, "TOPRIGHT", 0, 0)
		end
	else
		if not arrowList then
			arrowList = {}
			for id in pairs(arrows) do
				tinsert(arrowList, id)
			end
			sort(arrowList, function(a, b)
				if arrows[a] == arrows[b] then
					return a > b
				else
					return arrows[a] > arrows[b]
				end
			end)
			for i, id in ipairs(arrowList) do
				arrowMenu.args[i] = { type = "execute", order = i, arg1 = id, func = ammoFunc }
				arrowMenu.args[i].name, arrowMenu.args[i].icon, arrowMenu.args[i].link = self:GetEnchantmentName(id)
			end
			arrowMenu.args[#arrowMenu.args + 1] = { type = "execute", order = #arrowMenu.args + 1, arg1 = nil, func = ammoFunc, name = "화살 제거", desc = "화살을 제거합니다." }
			LDM:RegisterMenu("InvenSimulatorArrowMenu", arrowMenu)
		end
		if LDM:IsOpen("InvenSimulatorArrowMenu") then
			LDM:CloseMenu(1)
		else
			LDM:OpenMenu("InvenSimulatorArrowMenu", "TOPLEFT", self.ammoSlot, "TOPRIGHT", 0, 0)
		end
	end
end

local enchantmentName = InvenSimulatorUI.database.enchantmentName
local enchantmentID = InvenSimulatorUI.database.enchantmentID

local _enchantDB = {}
local realLoc, trc, eid
for loc, table in pairs(enchantDB) do
	realLoc = loc:match("INVTYPE_(.+)_(.+)")
	if realLoc then
		realLoc = "INVTYPE_"..realLoc
	else
		realLoc = loc
	end
	for _, enchants in pairs(table) do
		for _, id in ipairs(enchants) do
			eid = enchantmentID[id]
			if eid then
				_enchantDB[eid] = _enchantDB[eid] or {}
				_enchantDB[eid][realLoc] = id
			end
		end
	end
end

function InvenSimulatorUI:GetEnchantmentLink(code, loc)
	if _enchantDB[code] and _enchantDB[code][loc] then
		if _enchantDB[code][loc] > 0 then
			return "item:".._enchantDB[code][loc], GetItemIcon(_enchantDB[code][loc])
		else
			return "enchant:"..(-_enchantDB[code][loc]), select(3, GetSpellInfo(-_enchantDB[code][loc]))
		end
	end
	return nil, nil
end

local name, icon, link

function InvenSimulatorUI:GetEnchantmentName(code)
	if enchantmentID[code] then
		if type(enchantmentID[code]) == "number" then
			if code > 0 then
				name = enchantmentName[enchantmentID[code]] or GetItemInfo(code)
				icon = GetItemIcon(code)
				link = "item:"..code
			else
				name = enchantmentName[enchantmentID[code]] or gsub(GetSpellInfo(-code), "(.+) 마법부여 %- ", "")
				icon = select(3, GetSpellInfo(-code))
				link = "enchant:"..(-code)
			end
		elseif code > 0 then
			name = enchantmentID[code]
			icon = GetItemIcon(code)
			link = "item:"..code
		else
			name = enchantmentID[code]
			icon = select(3, GetSpellInfo(-code))
			link = "enchant:"..(-code)
		end
	else
		name, icon, link = code
	end
	return name, icon, link, enchantmentID[code]
end