TradeSkillFrame_LoadUI()

local IC = CreateFrame("Frame", "InvenCraftInfo2", TradeSkillFrame)
IC:SetScript("OnEvent", function(self, event, ...) self[event](self, ...) end)
IC:RegisterEvent("PLAYER_LOGIN")

local _G = getfenv(0)
local ipairs = _G.ipairs
local select = _G.select
local tonumber = _G.tonumber
local tinsert = _G.table.insert
local twipe = _G.table.wipe
local GetSpellInfo = _G.GetSpellInfo
local GetSpellLink = _G.GetSpellLink
local IsTradeSkillLinked = _G.IsTradeSkillLinked

MAX_TRADE_SKILL_LEVEL = PROFESSION_RANKS[#PROFESSION_RANKS][1]

BINDING_HEADER_INVENCRAFTINFO = "인벤 전문기술 정보 2"
BINDING_NAME_INVENCRAFTINFO_TOGGLE = "전문기술창 열기/닫기"
BINDING_NAME_INVENCRAFTINFO_OPTION = "설정창 열기"
SLASH_INVENCRAFTINFO1 = "/ici"
SLASH_INVENCRAFTINFO2 = "/인벤전문기술"
SLASH_INVENCRAFTINFO3 = "/invencraftinfo"
SlashCmdList["INVENCRAFTINFO"] = function() IC:OnClick() end

function IC:PLAYER_LOGIN()
	self.PLAYER_LOGIN = nil
	self:UnregisterEvent("PLAYER_LOGIN")
	self.playerName = UnitName("player")
	self.playerRealm = GetRealmName()
	self.playerRace = select(4, GetPlayerInfoByGUID(UnitGUID("player")))
	self.playerFaction = UnitFactionGroup("player") == "Horde" and 1 or 2
	local LBDB = LibStub("LibBlueDB-1.0")
	local function newTable() return {} end
	InvenCraftInfo2DB = InvenCraftInfo2DB or {}
	self.db = LBDB:RegisterDB(InvenCraftInfo2DB, {
		pos = { "CENTER", 0, 0 },
		title = true,
		reagent = true,
		craftable = true,
		drop = true,
		use = true,
		scale = 1,
		minimapButton = { show = true, dragable = true, angle = 120 },
	}, newTable)
	self.db.links = nil
	InvenCraftInfo2LinkDB = InvenCraftInfo2LinkDB or {}
	InvenCraftInfo2LinkDB[self.playerRealm] = InvenCraftInfo2LinkDB[self.playerRealm] or {}
	InvenCraftInfo2LinkDB[self.playerRealm][self.playerFaction] = InvenCraftInfo2LinkDB[self.playerRealm][self.playerFaction] or {}
	self.linkdb = InvenCraftInfo2LinkDB[self.playerRealm][self.playerFaction]
	InvenCraftInfo2CharDB = InvenCraftInfo2CharDB or {}
	self.chardb = LBDB:RegisterDB(InvenCraftInfo2CharDB, {
		select = 1,
	}, newTable)
	self.tradeSkillLinkParser = "trade:(%d+):(%d+):(%d+):([0-9A-Fa-f]+):([A-Za-z0-9+/]+)"
	self.linkCode = "trade:%d:"..MAX_TRADE_SKILL_LEVEL..":"..MAX_TRADE_SKILL_LEVEL..":"..UnitGUID("player"):gsub("0x0+", "")..":%s"
	self.skillCode = { 185, 171, 197, 165, 164, 202, 333, 755, 773, 186, 129 }
	self.skillID = { 2550, 2259, 3908, 2108, 2018, 4036, 7411, 25229, 45363, 2656, 3273 }
	self.needSideTab = { true, true, true, true, true, true, true, true, true }
	self.clearfunc = {}
	self.skillName, self.skillName2, self.skillButton = {}, {}, {}
	for p, v in ipairs(self.skillID) do
		self.skillName[p] = GetSpellInfo(v)
		self.skillName2[self.skillName[p]] = p
	end
	self.runeforging = GetSpellInfo(53428)
	tinsert(self.skillName, self.runeforging)
	for p, v in pairs(self.skillName) do
		self.skillButton[v] = CreateFrame("Button", nil, WorldFrame, "SecureActionButtonTemplate")
		self.skillButton[v]:SetAttribute("type", "spell")
		self.skillButton[v]:SetAttribute("spell", v)
	end
	self.newSkillName = { [GetSpellInfo(2575)] = GetSpellInfo(2656) }
	if TradeSkillFrame:IsShown() then
		CloseTradeSkill()
		HideUIPanel(TradeSkillFrame)
	end
	UIPanelWindows["TradeSkillFrame"] = nil
	tinsert(UISpecialFrames, "TradeSkillFrame")
	self.tooltip = CreateFrame("GameTooltip", nil, self)
	TradeSkillFrame:UnregisterAllEvents()
	self:RegisterEvent("TRADE_SKILL_SHOW")
	self:RegisterEvent("TRADE_SKILL_CLOSE")
	self:RegisterEvent("UPDATE_TRADESKILL_RECAST")
	self:RegisterEvent("CHAT_MSG_SYSTEM")
	self:RegisterEvent("PLAYER_ENTERING_WORLD")
	self:RegisterEvent("UPDATE_TICKET")
	LibStub("LibItemTooltip-2.0"):Register(self, "ProcessTooltip")
	LibStub("LibMapButton-1.1"):CreateButton(self, "InvenCraftInfo2MapButton", "Interface\\AddOns\\InvenCraftInfo2\\icon.tga", 120, InvenCraftInfo2DB.minimapButton)
	LibStub("LibDataBroker-1.1"):NewDataObject("InvenCraftInfo2", {
		type = "launcher",
		text = "ICI2",
		OnClick = self.OnClick,
		icon = "Interface\\AddOns\\InvenCraftInfo2\\icon.tga",
		OnTooltipShow = function(tooltip)
			if tooltip and tooltip.AddLine then
				IC:OnTooltip(tooltip)
			end
		end,
	})
	self.optionFrame = CreateFrame("Frame", "InvenCraftInfo2OptionFrame", InterfaceOptionsFramePanelContainer)
	self.optionFrame:Hide()
	self.optionFrame.name = "인벤 전문기술 정보 2"
	self.optionFrame:SetScript("OnShow", function(self)
		self:SetScript("OnShow", nil)
		LoadAddOn("InvenCraftInfo2_Option")
	end)
	InterfaceOptions_AddCategory(self.optionFrame)
end

function IC:AddMessage(msg)
	DEFAULT_CHAT_FRAME:AddMessage("|cffffff00Inven Craft Info|r의 "..msg)
end

function IC:LoadUI()
	if self.listButtons then
		return true
	else
		LoadAddOn("InvenCraftInfo2_UI")
		if self.listButtons then
			InvenCraftInfo2FavoriteDB = InvenCraftInfo2FavoriteDB or {}
			self.favoritedb = InvenCraftInfo2FavoriteDB
			collectgarbage()
			return true
		end
	end
	self:AddMessage("추가 구성 요소가 없습니다: UI")
	return nil
end

function IC:LoadDB()
	if self.GetLinkCode then
		return true
	else
		LoadAddOn("InvenCraftInfo2_DB")
		if self.GetLinkCode then
			collectgarbage()
			return true
		end
	end
	self:AddMessage("추가 구성 요소가 없습니다: DB")
	return nil
end

function IC:OnClick(button)
	if button == "RightButton" then
		if InterfaceOptionsFramePanelContainer.displayedPanel == IC.optionFrame then
			InterfaceOptionsFrameOkay_OnClick()
		else
			InterfaceOptionsFrame_OpenToCategory(IC.optionFrame)
		end
	elseif TradeSkillFrame:IsShown() then
		CloseTradeSkill()
		HideUIPanel(TradeSkillFrame)
	else
		if type(IC.chardb.select) == "string" and select(2, GetSpellLink(IC.chardb.select)) then
			IC.skillButton[IC.chardb.select]:Click()
		else
			IC:LoadUI()
			if IC.skillID[IC.chardb.select] and IC.needSideTab[IC.chardb.select] and IC.sideTabs[IC.chardb.select] then
				IC.sideTabs[IC.chardb.select]:Click()
			elseif IC.bottomTabs[1]:IsShown() then
				IC.chardb.select = IC.bottomTabs[1]:GetText()
				IC.skillButton[IC.chardb.select]:Click()
			else
				IC.chardb.select = 1
				IC.sideTabs[1]:Click()
			end
		end
	end
end

function IC:OnTooltip(tooltip)
	tooltip = tooltip or GameTooltip
	tooltip:AddLine("Inven Craft Info 2 v"..GetAddOnMetadata("InvenCraftInfo2", "Version"))
	tooltip:AddLine(GetAddOnMetadata("InvenCraftInfo2", "X-Website"), 1, 1, 1)
	tooltip:AddLine("좌클릭: 전문기술창 열기", 1, 1, 0)
	tooltip:AddLine("우클릭: 옵션창 열기", 1, 1, 0)
end

function IC:TRADE_SKILL_SHOW()
	self:UnregisterEvent("TRADE_SKILL_SHOW")
	if self:LoadUI() then
		TradeSkillFrame_Show()
	end
end

function IC:TRADE_SKILL_CLOSE()
	self:UnregisterEvent("TRADE_SKILL_UPDATE")
	self:UnregisterEvent("TRADE_SKILL_FILTER_UPDATE")
	self:UnregisterEvent("SKILL_LINES_CHANGED")
	self:UnregisterEvent("GUILD_RECIPE_KNOWN_BY_MEMBERS")
	if not self.passGarbage then
		for func in pairs(self.clearfunc) do
			func(self)
		end
		collectgarbage()
	end
end

function IC:UPDATE_TRADESKILL_RECAST()
	if TradeSkillFrame:IsShown() then
		TradeSkillInputBox:SetNumber(GetTradeskillRepeatCount())
	end
end

local learn = ERR_LEARN_ABILITY_S:gsub("%%s", "(.+)")
local learn2 = ERR_LEARN_RECIPE_S:gsub("%%s", "(.+)")
local unlearn = ERR_SPELL_UNLEARNED_S:gsub("%%s", "(.+)")

function IC:CHAT_MSG_SYSTEM(msg)
	if msg:find(learn) or msg:find(learn2) or msg:find(unlearn) then
		self:PLAYER_ENTERING_WORLD()
	end
end

function IC:SaveSkillCode(id)
	if self.skillID[id] and select(2, GetSpellLink(self.skillName[id])) then
		self.linkdb[id] = self.linkdb[id] or {}
		self.linkdb[id][self.playerName] = select(5, select(2, GetSpellLink(self.skillName[id])):match(self.tradeSkillLinkParser))
	end
end

function IC:RemoveSkillCode(id)
	if self.linkdb[id] and self.linkdb[id][self.playerName] then
		self.linkdb[id][self.playerName] = nil
		if not next(self.linkdb[id]) then
			self.linkdb[id] = nil
		end
	end
	return nil
end

function IC:PLAYER_ENTERING_WORLD()
	for i, name in ipairs(self.skillName) do
		if self.skillID[i] and select(2, GetSpellLink(self.skillName[i])) then
			self:SaveSkillCode(i)
		else
			self:RemoveSkillCode(i)
		end
	end
	if self.bottomTabs then
		self:UpdateBottomTabs()
	end
end

function IC:UPDATE_TICKET()
	self:UnregisterEvent("UPDATE_TICKET")
	self.UPDATE_TICKET = nil
	self:PLAYER_ENTERING_WORLD()
end