local _G = _G
local type = _G.type
local pairs = _G.pairs
local ipairs = _G.ipairs
local unpack = _G.unpack
local select = _G.select
local tonumber = _G.tonumber
local GetItemInfo = _G.GetItemInfo
local GetItemIcon = _G.GetItemIcon
local GetItemGem = _G.GetItemGem

local core = InvenSimulatorUI
local ie = CreateFrame("Frame", "InvenSimulatorItemEnchantingFrame", UIParent)
ie:Hide()
ie:SetToplevel(true)
ie:SetScript("OnShow", function(self) self:CreateFrame() end)
core.itemEnchantingFrame = ie

local LIS = LibStub("LibItemSpec-2.0")

function core:OpenItemEnchantingFrame(slot)
	if slot and self.db.items[slot] then
		if self:GetNumSocket(self.db.items[slot]) > 0 or self:IsEnchantable(self.db.items[slot]) then
			core:ShowTop(ie)
			ie.openSlot = slot
			ie:SetItem(self.db.items[slot])
		elseif ie:IsShown() then
			ie:Hide()
		end
	elseif ie:IsShown() then
		ie:Hide()
	end
end

function ie:CreateFrame()
	if not core.db.itemEnchantPos then
		core.db.itemEnchantPos = { "CENTER", 0, 0 }
	end
	self.levelElements = {}
	self:SetWidth(336)
	self:SetHeight(351)
	self:SetPoint(unpack(core.db.itemEnchantPos))
	self:EnableMouse(true)
	self:SetToplevel(true)
	self:SetMovable(true)
	self:SetClampedToScreen(true)
	self:RegisterForDrag("LeftButton", "RightButton")
	self:SetScript("OnDragStart", self.StartMoving)
	self:SetScript("OnDragStop", function(self)
		self:StopMovingOrSizing()
		InvenSimulatorCharDB.itemEnchantPos[1], _, _, InvenSimulatorCharDB.itemEnchantPos[2], InvenSimulatorCharDB.itemEnchantPos[3] = self:GetPoint()
	end)
	self:SetScript("OnShow", function() PlaySound("igCharacterInfoOpen") end)
	self:SetScript("OnHide", function(self)
		PlaySound("igCharacterInfoClose")
		self.openSlot = nil
	end)
	self.frame = self:CreateTexture(nil, "BORDER")
	self.frame:SetWidth(512)
	self.frame:SetHeight(376)
	self.frame:SetPoint("TOPLEFT", -18, 14)
	self.frame:SetTexture("Interface\\LFGFrame\\LFMFrame")
	self.frame:SetTexCoord(0, 1, 0, 0.6953125)
	self.frameBottom = self:CreateTexture(nil, "BORDER")
	self.frameBottom:SetWidth(512)
	self.frameBottom:SetHeight(12)
	self.frameBottom:SetPoint("TOP", self.frame, "BOTTOM")
	self.frameBottom:SetTexture("Interface\\LFGFrame\\LFGParentFrame")
	self.frameBottom:SetTexCoord(0, 1, 0.837, 0.8604375)
	self.portrait = self:CreateTexture(nil, "BACKGROUND")
	self.portrait:SetWidth(64)
	self.portrait:SetHeight(64)
	self.portrait:SetPoint("TOPLEFT", -6, 9)
	self.title = self:CreateFontString(nil, "OVERLAY", "GameFontHighlight")
	self.title:SetHeight(14)
	self.title:SetText(InvenSimulator.addonName.." - 아이템 강화")
	self.title:SetPoint("TOP", 17, -3)
	self.closeButton = CreateFrame("Button", nil, self, "UIPanelCloseButton")
	self.levelElements[self.closeButton] = 1
	self.closeButton:SetPoint("CENTER", self, "TOPRIGHT", -11, -10)
	self.tooltipBorder = self:CreateTexture(nil, "ARTWORK")
	self.tooltipBorder:SetWidth(318)
	self.tooltipBorder:SetHeight(281)
	self.tooltipBorder:SetPoint("TOP", -2, -81)
	self.tooltipBorder:SetTexture("Interface\\ItemSocketingFrame\\UI-ItemSocketingFrame")
	self.tooltipBorder:SetTexCoord(0.0399, 0.661, 0.15, 0.69883)
	self.tooltip = CreateFrame("GameTooltip", "InvenSimulatorItemEnchantingFrameTooltip", self, "GameTooltipTemplate")
	self.levelElements[self.tooltip] = 1
	self.tooltip:SetFrameStrata(self:GetFrameStrata())
	self.tooltip:SetBackdrop(nil)
	self.tempTooltip = CreateFrame("GameTooltip", "InvenSimulatorItemEnchantingFrameTempTooltip", self, "GameTooltipTemplate")
	self.tempTooltip.left = { InvenSimulatorItemEnchantingFrameTempTooltipTextLeft1 }
	self.tempTooltip.right = { InvenSimulatorItemEnchantingFrameTempTooltipTextRight1 }
	self.tempTooltip.texture = {}
	self.tempTooltip.textureIcon = {}
	self.socket = CreateFrame("Frame", nil, self)
	self.levelElements[self.socket] = 1
	self.socket:SetScale(0.9)
	self.socket:SetWidth(40)
	self.socket:SetHeight(40)
	self.socket:SetPoint("TOP", 10, -38)
	local function buttonOnClick(self)
		if self.buttonType == "enchant" then
			InvenSimulatorUI:OpenEnchantMenu(self)
		else
			InvenSimulatorUI:OpenGemMenu(self)
		end
	end
	local function buttonOnEnter(self)
		if self.link then
			GameTooltip:SetOwner(self, "ANCHOR_RIGHT")
			GameTooltip:SetHyperlink(self.link)
			if self.buttonType ~= "enchant" and self.tooltip then
				GameTooltipTextRight1:SetText("|cffffffff"..self.tooltip)
				GameTooltipTextRight1:Show()
			end
			GameTooltip:Show()
		elseif self.tooltip then
			GameTooltip:SetOwner(self, "ANCHOR_RIGHT")
			GameTooltip:AddLine(self.tooltip)
			GameTooltip:Show()
		else
			GameTooltip:Hide()
		end
	end
	for i = 1, 4 do
		self.socket[i] = CreateFrame("Button", "InvenSimulatorItemEnchantingFrameSocket"..i, self.socket)
		self.levelElements[self.socket[i]] = 2
		self.socket[i]:SetWidth(40)
		self.socket[i]:SetHeight(40)
		self.socket[i].border = self.socket[i]:CreateTexture(nil, "BORDER")
		self.socket[i].border:SetTexture("Interface\\ItemSocketingFrame\\UI-ItemSockets")
		self.socket[i].border:SetWidth(72)
		self.socket[i].border:SetHeight(74)
		self.socket[i].border:SetPoint("CENTER")
		self.socket[i].border:SetTexCoord(0.71875, 1, 0.7109375, 1)
		self.socket[i].background = self.socket[i]:CreateTexture(nil, "BORDER")
		self.socket[i].background:SetTexture("Interface\\ItemSocketingFrame\\UI-ItemSockets")
		self.socket[i].background:SetWidth(72)
		self.socket[i].background:SetHeight(74)
		self.socket[i].background:SetPoint("CENTER")
		self.socket[i].icon = self.socket[i]:CreateTexture(nil, "ARTWORK")
		self.socket[i].icon:SetWidth(38)
		self.socket[i].icon:SetHeight(38)
		self.socket[i].icon:SetPoint("CENTER")
		self.socket[i].icon:SetTexCoord(0.03, 0.97, 0.03, 0.97)
		self.socket[i].brackets = CreateFrame("Frame", nil, self.socket[i])
		self.socket[i].brackets:SetAllPoints()
		self.socket[i].closedBracket = self.socket[i].brackets:CreateTexture(nil, "ARTWORK")
		self.socket[i].closedBracket:SetTexture("Interface\\ItemSocketingFrame\\UI-ItemSockets")
		self.socket[i].closedBracket:SetWidth(53)
		self.socket[i].closedBracket:SetHeight(53)
		self.socket[i].closedBracket:SetPoint("CENTER")
		self.socket[i].closedBracket:SetTexCoord(0.5546875, 0.7578125, 0, 0.20703125)
		self.socket[i].openBracket = self.socket[i].brackets:CreateTexture(nil, "ARTWORK")
		self.socket[i].openBracket:SetTexture("Interface\\ItemSocketingFrame\\UI-ItemSockets")
		self.socket[i].openBracket:SetWidth(61)
		self.socket[i].openBracket:SetHeight(57)
		self.socket[i].openBracket:SetPoint("CENTER")
		self.socket[i].openBracket:SetTexCoord(0.7578125, 0.9921875, 0, 0.22265625)
		self.socket[i]:SetPushedTexture("Interface\\Buttons\\UI-Quickslot-Depress")
		self.socket[i]:SetHighlightTexture("Interface\\Buttons\\ButtonHilight-Square", "ADD")
		self.socket[i]:SetScript("OnClick", buttonOnClick)
		self.socket[i]:SetScript("OnEnter", buttonOnEnter)
		self.socket[i]:SetScript("OnLeave", GameTooltip_Hide)
		if i == 1 then
			self.socket[i]:SetPoint("LEFT", self.socket)
		else
			self.socket[i]:SetPoint("LEFT", self.socket[i - 1], "RIGHT", 20, 0)

		end
	end
end

local socketInfo = {
	["M"] = { 57, 52, 0.171875, 0.3984375, 0.40234375, 0.609375, 0.5546875, 0.7578125, 0, 0.20703125, 0.7578125, 0.9921875, 0, 0.22265625 },
	["R"] = { 43, 43, 0.1796875, 0.34375, 0.640625, 0.80859375, 0.5546875, 0.7578125, 0.4765625, 0.68359375, 0.7578125, 0.9921875, 0.4765625, 0.69921875 },
	["Y"] = { 43, 43, 0, 0.16796875, 0.640625, 0.80859375, 0.5546875, 0.7578125, 0, 0.20703125, 0.7578125, 0.9921875, 0, 0.22265625 },
	["B"] = { 43, 43, 0.3515625, 0.51953125, 0.640625, 0.80859375, 0.5546875, 0.7578125, 0.23828125, 0.4453125, 0.7578125, 0.9921875, 0.23828125, 0.4609375} ,
}
socketInfo["N"] = socketInfo["R"]
socketInfo["E"] = socketInfo["R"]

local socketTooltip = { ["M"] = "얼개 보석 홈", ["R"] = "붉은색 보석 홈", ["Y"] = "노란색 보석 홈", ["B"] = "푸른색 보석 홈", ["N"] = "다색 보석 홈", ["E"] = "아이템 강화" }
local buttonTypes = { ["M"] = "metagem", ["R"] = "gem", ["Y"] = "gem", ["B"] = "gem", ["N"] = "gem", ["E"] = "enchant"  }
local socketIcon = {
	["M"] = "Interface\\ItemSocketingFrame\\UI-EmptySocket-Meta",
	["R"] = "Interface\\ItemSocketingFrame\\UI-EmptySocket-Red",
	["Y"] = "Interface\\ItemSocketingFrame\\UI-EmptySocket-Yellow",
	["B"] = "Interface\\ItemSocketingFrame\\UI-EmptySocket-Blue",
	["N"] = "Interface\\ItemSocketingFrame\\UI-EmptySocket",
	["E"] = "Interface\\Icons\\Trade_Engraving",
}

function ie:SetSocketButton(id, color, icon)
	if self.socket[id] then
		if color and socketInfo[color] then
			self.socket[id].buttonType = buttonTypes[color]
			self.socket[id].tooltip = socketTooltip[color]
			self.socket[id].tooltipIcon = socketIcon[color]
			self.socket[id].background:SetWidth(socketInfo[color][1])
			self.socket[id].background:SetHeight(socketInfo[color][2])
			self.socket[id].background:SetTexCoord(socketInfo[color][3], socketInfo[color][4], socketInfo[color][5], socketInfo[color][6])
			if color == "R" or color == "Y" or color == "B" then
				self.socket[id].background:SetDesaturated(nil)
				self.socket[id].closedBracket:SetDesaturated(nil)
				self.socket[id].openBracket:SetDesaturated(nil)
			else
				self.socket[id].background:SetDesaturated(true)
				self.socket[id].closedBracket:SetDesaturated(true)
				self.socket[id].openBracket:SetDesaturated(true)
			end
			if color == "E" then
				self.socket[id].icon:SetTexture(icon or "")
				self.socket[id].openBracket:Hide()
				self.socket[id].closedBracket:Hide()
			elseif icon then
				self.socket[id].icon:SetTexture(icon)
				self.socket[id].closedBracket:SetTexCoord(socketInfo[color][7], socketInfo[color][8], socketInfo[color][9], socketInfo[color][10])
				self.socket[id].closedBracket:Show()
				self.socket[id].openBracket:Hide()
			else
				self.socket[id].icon:SetTexture("")
				self.socket[id].openBracket:SetTexCoord(socketInfo[color][11], socketInfo[color][12], socketInfo[color][13], socketInfo[color][14])
				self.socket[id].openBracket:Show()
				self.socket[id].closedBracket:Hide()
			end
			self.socket[id]:Show()
		else
			self.socket[id]:Hide()
		end
	end
end

local text, textR, r, g, b, rR, gR, bR, start, copyStart, endLine, runCopy, enchantText, enchantIcon, texturePos
local gems, enchant, socketText, numSocket, numSocket2, gemIndex, gemLink = {}

local function tooltipOnUpdate(tooltip)
	tooltip:Show()
	tooltip:SetScript("OnUpdate", nil)
end

local function copy(line, icon, forceText, forceR, forceG, forceB)
	if ie.tempTooltip.left[line] and ie.tempTooltip.left[line]:IsShown() then
		text = forceText or ie.tempTooltip.left[line]:GetText()
		if forceR and forceG and forceB then
			r, g, b = forceR, forceG, forceB
		else
			r, g, b = ie.tempTooltip.left[line]:GetTextColor()
			if icon and not (r < 0.6 and g < 0.6 and b < 0.6) then
				r, g, b = 1, 1, 1
			end
		end
		if line ~= 1 and r == 0 and g > 0.99 and b == 0 and enchantText == nil then
			if not (text:find("^방어도 (%d+)$") or text:find("보석 장착 보너스:") or text:find("착용 효과:") or text:find("사용 효과:") or text:find("발동 효과:") or text:find("변신 상태") or text == "상급") then
				enchantText = text
			end
		end
		if r > 0.9 and g < 0.2 and b < 0.2 then
			r, g, b = 0, 1, 0
		end
		if ie.tempTooltip.right[line] and ie.tempTooltip.right[line]:IsShown() then
			textR = ie.tempTooltip.right[line]:GetText()
			rR, gR, bR = ie.tempTooltip.right[line]:GetTextColor()
			if rR > 0.9 and gR < 0.2 and bR < 0.2 then
				rR, gR, bR = 1, 1, 1
			end
			ie.tooltip:AddDoubleLine(text, textR, r, g, b, rR, gR, bR, 1)
		else
			ie.tooltip:AddLine(text, r, g, b, 1)
		end
		if icon then
			ie.tooltip:AddTexture(icon)
		end
		return text
	end
	return nil
end

local skipText = { "직업:", "마법부여 (.+) %((%d+)%)", "요구 사항:", "마법부여 유효 요구 레벨 (%d+)", "종족: (.+)", "아이템 레벨 (%d+)", "^"..ITEM_QUALITY0_DESC.."$", "^"..ITEM_QUALITY1_DESC.."$", "^"..ITEM_QUALITY2_DESC.."$", "^"..ITEM_QUALITY3_DESC.."$", "^"..ITEM_QUALITY4_DESC.."$", "^"..ITEM_QUALITY5_DESC.."$", "^"..ITEM_QUALITY6_DESC.."$", "^"..ITEM_QUALITY7_DESC.."$" }
local addSocketCode = { [3729] = true, [3723] = true, [3717] = true }

function ie:SetItem(link)
	if type(link) == "string" and link:find("item:(%d+)") then
		self.tempTooltip:SetOwner(UIParent, "ANCHOR_NONE")
		self.tempTooltip:SetHyperlink(link)
		self.tempTooltip:Show()
		self.itemType1, _, self.itemType2 = select(7, GetItemInfo(link))
		SetPortraitToTexture(self.portrait, GetItemIcon(link))
		if InvenSimulatorItemEnchantingFrameTempTooltipMoneyFrame1 and InvenSimulatorItemEnchantingFrameTempTooltipMoneyFrame1:IsShown() then
			endLine = (select(2, InvenSimulatorItemEnchantingFrameTempTooltipMoneyFrame1:GetPoint()):GetName() or ""):match("InvenSimulatorItemEnchantingFrameTempTooltipTextLeft(%d+)")
			if endLine then
				endLine = tonumber(endLine) - 1
			else
				endLine = self.tempTooltip:NumLines()
			end
		else
			endLine = self.tempTooltip:NumLines()
		end
		for i = 1, 10 do
			self.tempTooltip.texture[i] = self.tempTooltip.texture[i] or _G["InvenSimulatorItemEnchantingFrameTempTooltipTexture"..i]
			if self.tempTooltip.texture[i] and self.tempTooltip.texture[i]:IsShown() and type(self.tempTooltip.texture[i]:GetTexture()) == "string" then
				texturePos = tonumber((select(2, self.tempTooltip.texture[i]:GetPoint()):GetName()):match("(%d+)") or "")
				if texturePos then
					self.tempTooltip.textureIcon[texturePos] = self.tempTooltip.texture[i]:GetTexture()
				end
			end
		end
		self.tooltip:SetOwner(self, "ANCHOR_NONE")
		self.tooltip:ClearLines()
		copy(1)
		enchantText = nil
		copyStart = nil
		start = select(9, GetItemInfo(link))
		start = _G[start]
		for i = 2, endLine do
			if not self.tempTooltip.left[i] then
				self.tempTooltip.left[i] = _G["InvenSimulatorItemEnchantingFrameTempTooltipTextLeft"..i]
				self.tempTooltip.right[i] = _G["InvenSimulatorItemEnchantingFrameTempTooltipTextRight"..i]
			end
			text = self.tempTooltip.left[i]:GetText()
			if text == start then
				copyStart = true
			elseif i == 2 and text == "상급" or text:find("^상급 ") and self.tempTooltip.textureIcon[i] == nil then
				copy(i, nil, "상급", 0, 1, 0)
			elseif text == " " then
				break
			end
			if copyStart and text then
				if text:find("팔보호구 보석 홈") or text:find("장갑 보석 홈") or text:find("허리띠 보석 홈") then
					copy(i, "Interface\\ItemSocketingFrame\\UI-EmptySocket", "다색 보석 홈", 0.5, 0.5, 0.5)
				elseif text:find("필요 조건:") then
					text = text:gsub("cff808080", "cffffffff")
					text = text:gsub("\n", "")
					copy(i, self.tempTooltip.textureIcon[i], text:gsub("필요 조건:(.+)", ""), 1, 1, 1)
				else
					runCopy = true
					for _, rp in ipairs(skipText) do
						if text:find(rp) then
							runCopy = nil
							break
						end
					end
					if runCopy then
						copy(i, self.tempTooltip.textureIcon[i])
					end
				end
			end
		end
		self.tooltip:SetMinimumWidth(275, 1)
		self.tooltip:Show()
		self.tooltip:ClearAllPoints()
		self.tooltip:SetPoint("TOP", self.tooltipBorder, "TOP", 0, -12)
		self.tooltip:SetScript("OnUpdate", tooltipOnUpdate)
		for p in pairs(self.tempTooltip.textureIcon) do
			self.tempTooltip.textureIcon[p] = nil
		end
		socketText = LIS:GetItemGemInfo(link)
		numSocket, socketText, gems[1], gems[2], gems[3] = core:GetNumSocket(link)
		enchant = core:GetEnchantID(link)
		if core:IsEnchantable(link) then
			socketText = "E"..socketText
			gemIndex = 0
			numSocket = numSocket + 1
		else
			gemIndex = 1
		end
		if numSocket == 0 then
			self:Hide()
		end
		for i = 1, numSocket do
			self.socket[i]:SetID(gemIndex)
			if gemIndex == 0 then
				self.socket[i].link, enchantIcon = core:GetEnchantmentLink(enchant, self.itemType2)
				self.socket[i].code = enchant or 0
				if self.socket[i].link then
					self:SetSocketButton(i, socketText:sub(i, i), enchantIcon or socketIcon["E"])
				elseif enchantText then
					self:SetSocketButton(i, socketText:sub(i, i), socketIcon["E"])
					self.socket[i].tooltip = "|cff00ff00"..enchantText.."|r"
				else
					self:SetSocketButton(i, socketText:sub(i, i), nil)
				end
			else
				gemLink = select(2, GetItemGem(link, gemIndex))
				if gemLink then
					self.socket[i].link = gemLink
					self.socket[i].code = addSocketCode[gems[gemIndex]] and 0 or gems[gemIndex]
					self:SetSocketButton(i, socketText:sub(i, i), GetItemIcon(gemLink))
				else
					self.socket[i].link = nil
					self.socket[i].code = 0
					self:SetSocketButton(i, socketText:sub(i, i), nil)
				end
			end
			gemIndex = gemIndex + 1
		end
		for i = numSocket + 1, #self.socket do
			self.socket[i]:Hide()
		end
		self.socket:SetWidth(40 + (numSocket - 1) * 60)
	end
end