local IC = InvenCraftInfo2

local _G = _G
local ipairs = _G.ipairs
local select = _G.select
local tonumber = _G.tonumber
local twipe = _G.table.wipe
local tinsert = _G.table.insert
local GetNumTradeSkills = _G.GetNumTradeSkills
local GetTradeSkillLine = _G.GetTradeSkillLine
local GetTradeSkillInfo = _G.GetTradeSkillInfo
local GetTradeSkillListLink = _G.GetTradeSkillListLink
local IsTradeSkillLinked = _G.IsTradeSkillLinked
local GetTradeSkillSelectionIndex = _G.GetTradeSkillSelectionIndex
local GetTradeSkillRecipeLink = _G.GetTradeSkillRecipeLink
local GetTradeSkillItemLink = _G.GetTradeSkillItemLink

local numSkills, skillName, skillRank, skillMaxRank, offset, index, selectedIndex, known, sourceCount, sourceWidth
local spellName, spellType, numAvailable, isExpanded, numSkillUps, showSkillUps, width, color, spellID, numHeaders, numCollapseHeader
local skipUpdate, newLinkCode
local temp = {}

IC.knownSpells, IC.selectedTab = {}, 0
IC.spellLocation = {}
IC.favoriteList, IC.favoriteHeader = {}, true

local function updateMySkillCode()
	newLinkCode = select(5, (GetTradeSkillListLink() or ""):match(IC.tradeSkillLinkParser))
	if newLinkCode ~= IC.currentSkillCode then
		IC.currentSkillCode = newLinkCode
		newLinkCode = nil
		if IC.currentSkillCode then
			IC:SaveSkillCode(IC.currentSkillID)
		end
	end
end

function TradeSkillFrame_Show()
	skipUpdate = true
	IC:UnregisterEvent("TRADE_SKILL_UPDATE")
	IC:UnregisterEvent("TRADE_SKILL_FILTER_UPDATE")
	IC:UnregisterEvent("SKILL_LINES_CHANGED")
	IC:UnregisterEvent("GUILD_RECIPE_KNOWN_BY_MEMBERS")
	IC:UnregisterEvent("TRADE_SKILL_NAME_UPDATE")
	StopTradeSkillRepeat()
	IC.loading:Show()
	TradeSkillSetFilter(-1, -1)
	TradeSkillOnlyShowMakeable(nil)
	TradeSkillOnlyShowSkillUps(nil)
	SetTradeSkillItemNameFilter("")
	IC.currentSkill = GetTradeSkillLine()
	IC.currentSkill = IC.newSkillName[IC.currentSkill] or IC.currentSkill
	IC.currentSkillID = IC.skillName2[IC.currentSkill]
	IC.currentSkillOwner = IsTradeSkillGuild() and "GUILD" or select(2, IsTradeSkillLinked())
	IC.selectedTab = 0
	if IC.linkedID and IC.currentSkillOwner == IC.playerName then
		-- 우측 탭
		for i, tab in ipairs(IC.sideTabs) do
			if tab:GetID() == IC.linkedID then
				tab:SetChecked(true)
				tab:RegisterForClicks("")
			else
				tab:SetChecked(nil)
				tab:RegisterForClicks("LeftButtonUp")
			end
		end
		IC.chardb.select = IC.linkedID
	else
		IC.linkedID = nil
		for _, tab in ipairs(IC.sideTabs) do
			tab:SetChecked(nil)
			tab:RegisterForClicks("LeftButtonUp")
		end
		if IC.currentSkillOwner then
			if IC.sideTabs[IC.currentSkillID] then
				ExpandTradeSkillSubClass(0)
				for i = 1, GetNumTradeSkills() do
					temp[IC:GetTradeSkillRecipeID(i) or 0] = true
				end
				IC.currentSkillCode = IC:GetLinkCode(IC.currentSkillID, temp)
				twipe(temp)
			else
				IC.currentSkillCode = nil
			end
		else
			-- 내 전문기술
			IC.selectedTab = IC.bottomTabsID[IC.currentSkill] or 0
			IC.chardb.select = IC.currentSkill
			IC.currentSkillCode = nil
			updateMySkillCode()
		end
	end
	PanelTemplates_UpdateTabs(IC)
	twipe(IC.knownSpells)
	if IC.currentSkillID and IC.currentSkillOwner then
		IC:HasSkillTable(IC.currentSkillID, IC.knownSpells)
	end
	TradeSkillCreateButton:Disable()
	TradeSkillCreateAllButton:Disable()
	FauxScrollFrame_SetOffset(TradeSkillListScrollFrame, 0)
	TradeSkillListScrollFrameScrollBar:SetMinMaxValues(0, 0)
	TradeSkillListScrollFrameScrollBar:SetValue(0)
	TradeSkillFrameSearchBox:SetText(SEARCH)
	TradeSkillOnlyShowMakeable(TradeSkillFrame.filterTbl.hasMaterials)
	TradeSkillOnlyShowSkillUps(TradeSkillFrame.filterTbl.hasSkillUp)
	SetPortraitToTexture(TradeSkillFramePortrait, GetTradeSkillTexture())
	ShowUIPanel(TradeSkillFrame)
	skipUpdate = nil
	IC:TRADE_SKILL_NAME_UPDATE()
	IC:TRADE_SKILL_UPDATE()
	IC:RegisterEvent("TRADE_SKILL_UPDATE")
	IC:RegisterEvent("TRADE_SKILL_FILTER_UPDATE")
	IC:RegisterEvent("SKILL_LINES_CHANGED")
	IC:RegisterEvent("GUILD_RECIPE_KNOWN_BY_MEMBERS")
	IC:RegisterEvent("TRADE_SKILL_NAME_UPDATE")
	CloseDropDownMenus()
end

function IC:TRADE_SKILL_NAME_UPDATE()
	self.currentSkillOwner = IsTradeSkillGuild() and "GUILD" or select(2, IsTradeSkillLinked())
	if IsTradeSkillGuild() then
		TradeSkillLinkButton:Hide()
		TradeSkillLinkNameButtonTitleText:SetFormattedText("<%s>", GUILD)
		TradeSkillLinkNameButton:Show()
		TradeSkillLinkNameButton:Disable()
	elseif self.linkedID and self.currentSkillOwner == self.playerName then
		TradeSkillLinkButton:Hide()
		TradeSkillLinkNameButton:Hide()
	elseif self.currentSkillOwner then
		TradeSkillLinkButton:Hide()
		TradeSkillLinkNameButtonTitleText:SetFormattedText("[%s]", self.currentSkillOwner)
		TradeSkillLinkNameButton:Show()
		TradeSkillLinkNameButton:Enable()
	else
		TradeSkillLinkNameButton:Hide()
		if GetTradeSkillListLink() then
			TradeSkillLinkButton:Show()
		else
			TradeSkillLinkButton:Hide()
		end
	end
end

function IC:SKILL_LINES_CHANGED()
	skillName, skillRank, skillMaxRank = GetTradeSkillLine()
	self.tradeSkillTitle:SetText(skillName)
	if IsTradeSkillGuild() or IC.currentSkill == self.runeforging then
		TradeSkillRankFrame:SetMinMaxValues(0, 1)
		TradeSkillRankFrame:SetValue(1)
		TradeSkillRankFrameSkillRank:SetText("")
	else
		if self.linkedID then
			skillRank = MAX_TRADE_SKILL_LEVEL + self:GetAddSkillRank(self.linkedID)
			skillMaxRank = skillRank
		end
		TradeSkillRankFrame:SetMinMaxValues(0, skillMaxRank)
		TradeSkillRankFrame:SetValue(skillRank)
		TradeSkillRankFrameSkillRank:SetFormattedText("%d/%d", skillRank, skillMaxRank)
	end
	TradeSkillRankFrame:Show()
	if not IC.currentSkillOwner then
		updateMySkillCode()
	end
end

function IC:TRADE_SKILL_UPDATE()
	self:SKILL_LINES_CHANGED()
	self:UpdateFavoriteList()
	if self.linkedID then
		self.statusbar:SetMinMaxValues(0, self.sideTabs[self.linkedID].num)
		self.statusbar:SetValue(self.sideTabs[self.linkedID].num)
		self.statusbar.text:SetFormattedText("%d/%d (100.0%%)", self.sideTabs[self.linkedID].num, self.sideTabs[self.linkedID].num)
	elseif self.currentSkillID and self.sideTabs[self.currentSkillID] and self.currentSkillCode then
		self.statusbar:SetMinMaxValues(0, self.sideTabs[self.currentSkillID].num)
		self.statusbar:SetValue(self:GetNumSkills(self.currentSkillID, self.currentSkillCode))
		self.statusbar.text:SetFormattedText("%d/%d (%.1f%%)", self.statusbar:GetValue(), self.sideTabs[self.currentSkillID].num, self.statusbar:GetValue() / self.sideTabs[self.currentSkillID].num * 100)
	else
		self.statusbar:SetValue(0)
		self.statusbar.text:SetText("")
	end
	TradeSkillFrame.selectedID = GetTradeSkillSelectionIndex()
	if TradeSkillFrame.selectedSkill then
		TradeSkillFrame.selectedID = 0
		for i = 1, self.numSkills do
			if self:GetTradeSkillRecipeID(i) == TradeSkillFrame.selectedSkill then
				TradeSkillFrame.selectedID = i
				break
			end
		end
	end
	if TradeSkillFrame.selectedID < 1 or TradeSkillFrame.selectedID > self.numSkills then
		if IC.favoriteList[2] then
			TradeSkillFrame.selectedID = IC.favoriteList[2]
		else
			TradeSkillFrame.selectedID = 0
			for i = 1, self.numSkills do
				if self:GetTradeSkillRecipeID(i) then
					TradeSkillFrame.selectedID = i
					break
				end
			end
		end
	end
	TradeSkillFrame_SetSelection(TradeSkillFrame.selectedID)
	TradeSkillFrame_Update()
end

function IC:TRADE_SKILL_FILTER_UPDATE()
	self:TRADE_SKILL_UPDATE()
end

function IC:UpdateFavoriteList()
	self.numSkills = GetNumTradeSkills()
	twipe(self.favoriteList)
	twipe(self.spellLocation)
	if self.numSkills > 0 and select(2, GetTradeSkillInfo(1)) == "header" then
		IC.loading:Hide()
		numHeaders, numCollapseHeader = 0, 0
		for i = 1, self.numSkills do
			spellType, _, isExpanded = select(2, GetTradeSkillInfo(i))
			if spellType == "header" then
				numHeaders = numHeaders + 1
				numCollapseHeader = numCollapseHeader + (isExpanded and 0 or 1)
			else
				spellID = IC:GetTradeSkillRecipeID(i)
				if spellID then
					self.spellLocation[spellID] = i
					if self.favoritedb[spellID] then
						tinsert(self.favoriteList, i)
					end
				end
			end
		end
		if #self.favoriteList > 0 then
			if not self.favoriteHeader then
				numCollapseHeader = numCollapseHeader + 1
				twipe(self.favoriteList)
			end
			tinsert(self.favoriteList, 1, 99999)
			numHeaders = numHeaders + 1
		end
		if numHeaders == numCollapseHeader then
			TradeSkillCollapseAllButton.collapsed = true
			TradeSkillCollapseAllButton:SetNormalTexture("Interface\\Buttons\\UI-PlusButton-Up")
		else
			TradeSkillCollapseAllButton.collapsed = nil
			TradeSkillCollapseAllButton:SetNormalTexture("Interface\\Buttons\\UI-MinusButton-Up")
		end
		TradeSkillCollapseAllButton:Enable()
		IC.addFavoriteButton:Show()
	else
		TradeSkillCollapseAllButton:SetNormalTexture("Interface\\Buttons\\UI-PlusButton-Up")
		TradeSkillCollapseAllButton:Disable()
		IC.addFavoriteButton:Hide()
		if self.currentSkill == self.runeforging or self.numSkills == 0 then
			IC.loading:Hide()
		end
	end
end

local function addSource(source, text, desc, texture)
	if sourceCount < #source then
		sourceCount = sourceCount + 1
		if text and desc then
			source[sourceCount].tooltipText = text.."("..desc..")"
		else
			source[sourceCount].tooltipText = text
		end
		source[sourceCount]:SetNormalTexture(texture)
		source[sourceCount]:Show()
		if sourceCount == 1 then
			sourceWidth = source[sourceCount]:GetWidth() + 2
		else
			sourceWidth = sourceWidth + source[sourceCount]:GetWidth() - 1
		end
	end
end

local function display(btn, index)
	if spellName then
		btn:SetWidth(width)
		btn:SetID(index)
		if spellType == "header" then
			btn:SetNormalFontObject(TradeSkillTypeColor[spellType].font)
			btn.r, btn.g, btn.b = TradeSkillTypeColor[spellType].r, TradeSkillTypeColor[spellType].g, TradeSkillTypeColor[spellType].b
			btn:SetText(spellName)
			btn:UnlockHighlight()
			if isExpanded then
				btn:SetNormalTexture("Interface\\Buttons\\UI-MinusButton-UP")
			else
				btn:SetNormalTexture("Interface\\Buttons\\UI-PlusButton-UP")
			end
			btn:SetHighlightTexture("Interface\\Buttons\\UI-PlusButton-Hilight")
			btn.highlight:Hide()
			btn.checked:Hide()
			btn.text:SetWidth(width - 23)
			btn.count:SetText(nil)
			for _, source in pairs(btn.source) do
				source:Hide()
			end
		else
			spellID = IC:GetTradeSkillRecipeID(index)
			if IC.linkedID then
				color = IC.itemQuality[IC:GetColorID(spellID)] or TradeSkillTypeColor.header
				btn.r, btn.g, btn.b = color.r, color.g, color.b
				btn.cr, btn.cg, btn.cb = TradeSkillTypeColor[spellType].r, TradeSkillTypeColor[spellType].g, TradeSkillTypeColor[spellType].b
			else
				color = TradeSkillTypeColor[spellType]
				btn.r, btn.g, btn.b = color.r, color.g, color.b
				btn.cr, btn.cg, btn.cb = color.r, color.g, color.b
			end
			btn:SetNormalFontObject(color.font)
			btn:SetText(" "..spellName)
			btn:SetNormalTexture("")
			btn:SetHighlightTexture("")
			sourceCount, sourceWidth = 0, 0
			if IC:IsTrainerSpell(spellID) then
				addSource(btn.source, MINIMAP_TRACKING_TRAINER_PROFESSION, select(2, IC:GetRequire(spellID)) or "???", "Interface\\GossipFrame\\TrainerGossipIcon")
			else
				if IC:IsDiscoverySpell(spellID) then
					addSource(btn.source, "발견", nil, "Interface\\GossipFrame\\GossipGossipIcon")
				end
				if IC:IsQuestSpell(spellID) then
					addSource(btn.source, QUESTS_LABEL, nil, "Interface\\GossipFrame\\AvailableQuestIcon")
				end
				if IC:IsFactionSpell(spellID) then
					addSource(btn.source, REPUTATION, nil, "Interface\\GossipFrame\\TaxiGossipIcon")
				elseif IC:IsSellSpell(spellID) then
					addSource(btn.source, TUTORIAL_TITLE20, nil, "Interface\\GossipFrame\\VendorGossipIcon")
				end
				if IC:IsDropSpell(spellID) then
					addSource(btn.source, LOOT, nil, "Interface\\GossipFrame\\BattleMasterGossipIcon")
				end
			end
			for i = sourceCount + 1, #btn.source do
				btn.source[i]:Hide()
			end
			if not(numSkillUps > 1 and spellType == "optimal") then
				numSkillUps = nil
			end
			if numAvailable > 0 then
				if numSkillUps then
					btn.count:SetFormattedText(" [%d] <+%d>", numAvailable, numSkillUps)
				else
					btn.count:SetFormattedText(" [%d]", numAvailable)
				end
			elseif numSkillUps then
				btn.count:SetFormattedText(" <+%d>", numSkillUps)
			else
				btn.count:SetText(nil)
			end
			TradeSkillFrameDummyString:SetText(btn.text:GetText())
			if (TradeSkillFrameDummyString:GetWidth() + btn.count:GetWidth() + sourceWidth) > (width - 23) then
				btn.text:SetWidth(width - btn.count:GetWidth() - 23 - sourceWidth)
			else
				btn.text:SetWidth(0)
			end
			if IC.knownSpells[spellID] then
				btn.checked:Show()
				btn.checked.learn = IC.knownSpells[spellID]
				if btn.checked.learn:find("d1") then
					btn.checked:SetNormalTexture("Interface\\Buttons\\UI-CheckBox-Check")
				else
					btn.checked:SetNormalTexture("Interface\\Buttons\\UI-CheckBox-Check-Disabled")
				end
			else
				btn.checked:Hide()
			end
			if index == selectedIndex then
				btn:LockHighlight()
				btn.highlight:SetVertexColor(btn.r, btn.g, btn.b)
				btn.highlight:Show()
				btn.count:SetVertexColor(1, 1, 1)
			else
				btn:UnlockHighlight()
				btn.highlight:Hide()
				if btn.enter then
					btn.count:SetVertexColor(1, 1, 1)
				else
					btn.count:SetVertexColor(btn.cr, btn.cg, btn.cb)
				end
			end
		end
		btn:Show()
	else
		btn:Hide()
	end
	return nil
end

function TradeSkillFrame_Update()
	if skipUpdate then return end
	numSkills = GetNumTradeSkills()
	if numSkills == 0 then
		for _, btn in ipairs(IC.listButtons) do
			btn:Hide()
		end
		TradeSkillListScrollFrame:Hide()
		TradeSkillFilterBar:SetWidth(317)
	else
		TradeSkillListScrollFrame:Show()
		numSkills = numSkills + #IC.favoriteList
		FauxScrollFrame_Update(TradeSkillListScrollFrame, numSkills, TRADE_SKILLS_DISPLAYED, TRADE_SKILL_HEIGHT)
		offset = FauxScrollFrame_GetOffset(TradeSkillListScrollFrame)
		selectedIndex = GetTradeSkillSelectionIndex()
		width = TradeSkillListScrollFrame:IsShown() and 295 or 317
		if TradeSkillFilterBar:IsShown() then
			offset = offset - 1
			IC.listButtons[1]:Hide()
			TradeSkillFilterBar:SetWidth(width)
		end
		showSkillUps = GetSpellLink(IC.currentSkill)
		for i = TradeSkillFilterBar:IsShown() and 2 or 1, TRADE_SKILLS_DISPLAYED do
			index = i + offset
			if index > numSkills then
				IC.listButtons[i]:Hide()
			else
				if IC.favoriteList[index] == 99999 then
					spellName, spellType, numAvailable, isExpanded, numSkillUps = "즐겨찾기", "header", nil, IC.favoriteHeader, 0
				else
					spellName, spellType, numAvailable, isExpanded, _, numSkillUps = GetTradeSkillInfo(IC.favoriteList[index] or (index - #IC.favoriteList))
					numSkillUps = showSkillUps and numSkillUps or 0
				end
				if display(IC.listButtons[i], IC.favoriteList[index] or (index - #IC.favoriteList)) then
					return
				end
			end
		end
	end
end

IC.clearfunc[function(self)
	numSkills, skillName, skillRank, skillMaxRank, offset, index, selectedIndex, known, sourceCount, sourceWidth = nil
	spellName, spellType, numAvailable, isExpanded, numSkillUps, showSkillUps, width, color, spellID, numHeaders, numCollapseHeader = nil
	self.currentSkill, self.currentSkillID, self.linkedID, self.currentSkillCode, self.currentSkillOwner, self.isGuildSkill = nil
	twipe(self.favoriteList)
	twipe(self.knownSpells)
	twipe(self.spellLocation)
end] = true