local IC = InvenCraftInfo2

local _G = _G
local pairs = _G.pairs
local select = _G.select
local abs = _G.math.abs
local ceil = _G.math.ceil
local sort = _G.table.sort
local twipe = _G.table.wipe
local tinsert = _G.table.insert
local GetItemCount = _G.GetItemCount
local GetTradeSkillInfo = _G.GetTradeSkillInfo
local GetTradeSkillItemLink = _G.GetTradeSkillItemLink
local SelectTradeSkill = _G.SelectTradeSkill
local GetNumTradeSkills = _G.GetNumTradeSkills
local GetTradeSkillIcon = _G.GetTradeSkillIcon
local GetTradeSkillNumMade = _G.GetTradeSkillNumMade
local GetTradeSkillTools = _G.GetTradeSkillTools
local GetTradeSkillCooldown = _G.GetTradeSkillCooldown
local GetTradeSkillDescription = _G.GetTradeSkillDescription
local GetTradeSkillNumReagents = _G.GetTradeSkillNumReagents
local GetTradeSkillReagentInfo = _G.GetTradeSkillReagentInfo
local GetTradeSkillReagentItemLink = _G.GetTradeSkillReagentItemLink
local GetTradeskillRepeatCount = _G.GetTradeskillRepeatCount
local GetTradeSkillListLink = _G.GetTradeSkillListLink
local IsTradeSkillLinked = _G.IsTradeSkillLinked
local IsTradeSkillGuild = _G.IsTradeSkillGuild
local ExpandTradeSkillSubClass = _G.ExpandTradeSkillSubClass
local CollapseTradeSkillSubClass = _G.CollapseTradeSkillSubClass
local BuildColoredListString = _G.BuildColoredListString
local GetGuildRecipeMember = _G.GetGuildRecipeMember
local GetGuildRecipeInfoPostQuery = _G.GetGuildRecipeInfoPostQuery

local spellID, spellName, spellType, numAvailable, isExpanded, altVerb, minMade, maxMade, creatable
local numReagents, reagentID, reagentName, reagentIcon, reagentCount, reagentCountPlayer, reagentCountBank, needUpdate, getNum

IC.reagentQue = {}

local function getQualityColor(id, index)
	if index then
		id = IC.itemQuality[IC:GetColorID(GetTradeSkillReagentItemLink(id, index))]
	else
		id = IC.itemQuality[IC:GetColorID(GetTradeSkillRecipeLink(id))] or TradeSkillTypeColor.header
	end
	if id then
		return id.r, id.g, id.b, 0.5
	else
		return 0, 0, 0, 0
	end
end

local function hideCreate()
	TradeSkillCreateButton:Hide()
	TradeSkillCreateAllButton:Hide()
	TradeSkillDecrementButton:Hide()
	TradeSkillInputBox:Hide()
	TradeSkillIncrementButton:Hide()
end

local function refreshDetail(self, timer)
	self.updateTimer = self.updateTimer + timer
	if self.updateTimer > 1 then
		self.updateTimer = 0
		TradeSkillFrame_SetSelection(TradeSkillFrame.selectedID)
	end
end

IC.getButtons = {}

local function getButtonOnEnter(self)
	GameTooltip:SetOwner(self, "ANCHOR_TOPLEFT")
	GameTooltip:AddLine("위치 보기", 1, 1, 1)
	GameTooltip:Show()
	SetCursor("INSPECT_CURSOR")
end

local function getButtonOnLeave(self)
	GameTooltip:Hide()
	SetCursor(nil)
end

local function getButtonOnClick(self)
	if self.npc then
		LoadAddOn("InvenCraftInfo2_Map")
		InvenCraftInfo2_Map:Hide()
		InvenCraftInfo2_Map:SetNpc(self.npc)
	end
end

local function createGetButton(id, text, npc, ...)
	if not IC.getButtons[id] then
		IC.getButtons[id] = CreateFrame("Button", nil, TradeSkillDetailScrollChildFrame)
		IC.getButtons[id]:SetNormalFontObject("GameFontHighlightSmallLeft")
		IC.getButtons[id]:SetPushedTextOffset(1, -1)
		IC.getButtons[id]:SetScript("OnEnter", getButtonOnEnter)
		IC.getButtons[id]:SetScript("OnLeave", getButtonOnLeave)
		IC.getButtons[id]:SetScript("OnClick", getButtonOnClick)
	end
	IC.getButtons[id]:Show()
	IC.getButtons[id]:SetText(text:trim())
	IC.getButtons[id]:SetSize(IC.getButtons[id]:GetTextWidth() + 1, IC.getButtons[id]:GetTextHeight() + 1)
	IC.getButtons[id]:SetPoint(...)
	if npc and npc > 0 then
		IC.getButtons[id].npc = npc
		IC.getButtons[id]:EnableMouse(true)
	else
		IC.getButtons[id].npc = nil
		IC.getButtons[id]:EnableMouse(nil)
	end
	return IC.getButtons[id]
end

local function setLabelPoint(label, num)
	if num > 0 then
		label:SetPoint("TOPLEFT", IC.getButtons[num], "BOTTOMLEFT", 0, -10)
	elseif TradeSkillDescription:GetText() then
		label:SetPoint("TOPLEFT", TradeSkillDescription, "BOTTOMLEFT", 0, -10)
	else
		label:SetPoint("TOPLEFT", TradeSkillDescription, 0, 0)
	end
end

local function checkLocation(...)
	for i = 1, select("#", ...) do
		reagentID = select(i, ...)
		if IC.spellLocation[reagentID] then
			return reagentID
		end
	end
	return nil
end

local dropText, dropID

function TradeSkillFrame_SetSelection(id)
	if id == 99999 then
		IC.favoriteHeader = not IC.favoriteHeader
		IC:UpdateFavoriteList()
		TradeSkillFrame_Update()
		return
	end
	spellName, spellType, numAvailable, isExpanded, altVerb = GetTradeSkillInfo(id)
	if not spellName or id < 1 or id > GetNumTradeSkills() then
		SelectTradeSkill(0)
		TradeSkillDetailScrollFrame:Hide()
		TradeSkillDetailScrollFrame:SetScript("OnUpdate", nil)
		TradeSkillFrame.selectedID, TradeSkillFrame.numAvailable, TradeSkillFrame.selectedSkill = 0, 0, nil
		TradeSkillViewGuildCraftersButton:Hide()
		TradeSkillGuildCraftersFrame:Hide()
		return hideCreate()
	elseif spellType == "header" then
		if isExpanded then
			CollapseTradeSkillSubClass(id)
		else
			ExpandTradeSkillSubClass(id)
		end
		return
	end
	SelectTradeSkill(id)
	TradeSkillFrame.selectedID = id
	TradeSkillFrame.selectedSkill = IC:GetTradeSkillRecipeID(id)
	spellID = nil
	for i = 1, #IC.reagentQue do
		if IC.spellLocation[IC.reagentQue[i]] then
			if IC.reagentQue[i] == TradeSkillFrame.selectedSkill then
				for j = i + 1, #IC.reagentQue do
					IC.reagentQue[j] = nil
				end
				spellID = true
				break
			end
		else
			break
		end
	end
	if not spellID then
		twipe(IC.reagentQue)
		IC.reagentQue[1] = TradeSkillFrame.selectedSkill
	end
	if #IC.reagentQue > 1 then
		IC.backParent:Show()
		IC.backParent.goto = IC.reagentQue[#IC.reagentQue - 1]
		IC.backParent.tooltipText = ("%s|1으로;로; 돌아가기"):format(GetTradeSkillInfo(IC.spellLocation[IC.backParent.goto]))
	else
		IC.backParent:Hide()
	end
	TradeSkillFrame.numAvailable = abs(numAvailable or 0)
	TradeSkillSkillIcon:SetNormalTexture(GetTradeSkillIcon(id))
	minMade,maxMade = GetTradeSkillNumMade(id)
	if maxMade > 1 then
		if minMade == maxMade then
			TradeSkillSkillIconCount:SetText(minMade)
		else
			TradeSkillSkillIconCount:SetFormattedText("%d-%d", minMade, maxMade)
			if TradeSkillSkillIconCount:GetWidth() > TradeSkillSkillIcon:GetWidth() then
				TradeSkillSkillIconCount:SetFormattedText("~%d", (minMade + maxMade) / 2)
			end
		end
	else
		TradeSkillSkillIconCount:SetText(nil)
	end
	IC.skillIconBorder:SetVertexColor(getQualityColor(id))
	spellID = TradeSkillFrame.selectedSkill
	if IC.favoritedb[spellID] then
		IC.addFavoriteButton.deleteIcon:Show()
	else
		IC.addFavoriteButton.deleteIcon:Hide()
	end
	TradeSkillSkillName:SetText(spellName)
	spellTools = BuildColoredListString(GetTradeSkillTools(id))
	if spellTools then
		TradeSkillRequirementLabel:SetFormattedText("%s %s", REQUIRES_LABEL, spellTools)
	else
		TradeSkillRequirementLabel:SetText(nil)
	end
	if IC.currentSkill == IC.runeforging then
		IC.detailRequire:SetText(nil)
	else
		IC.detailRequire:SetFormattedText("필요 숙련: %s%s", select(2, IC:GetRequire(spellID)) or "|cffff0000알 수 없음|r", IC:GetColor(spellID) or "")
	end
	if GetTradeSkillCooldown(id) then
		TradeSkillSkillCooldown:SetText(COOLDOWN_REMAINING.." "..SecondsToTime(GetTradeSkillCooldown(id)))
	else
		TradeSkillSkillCooldown:SetText(nil)
	end
	TradeSkillDescription:SetText(GetTradeSkillDescription(id))
	getNum = 0
	if IC:IsTrainerSpell(spellID) then
		setLabelPoint(IC.detailTrainerLabel, 0)
		IC.detailTrainerLabel:Show()
		getNum = getNum + 1
		createGetButton(getNum, MINIMAP_TRACKING_TRAINER_PROFESSION, nil, "TOPLEFT", IC.detailTrainerLabel, "BOTTOMLEFT", 0, 0)
		IC.detailDiscoveryLabel:Hide()
		IC.detailDropLabel:Hide()
		IC.detailSellLabel:Hide()
		IC.detailQuestLabel:Hide()
	else
		IC.detailTrainerLabel:Hide()
		dropText = IC:GetDiscoveryText(spellID)
		if dropText then
			IC.detailDiscoveryLabel:Show()
			setLabelPoint(IC.detailDiscoveryLabel, getNum)
			getNum = getNum + 1
			createGetButton(getNum, dropText, nil, "TOPLEFT", IC.detailDiscoveryLabel, "BOTTOMLEFT", 0, 0)
		else
			IC.detailDiscoveryLabel:Hide()
		end
		IC:GetDropInfo(spellID)
		if #IC.output > 0 then
			IC.detailDropLabel:Show()
			setLabelPoint(IC.detailDropLabel, getNum)
			for p, v in ipairs(IC.output) do
				dropID, dropText = v:match("^(%d+)_(.+)")
				getNum = getNum + 1
				createGetButton(getNum, dropText, tonumber(dropID), "TOPLEFT", p == 1 and IC.detailDropLabel or IC.getButtons[getNum - 1], "BOTTOMLEFT", 0, 0)
			end
			wipe(IC.output)
		else
			IC.detailDropLabel:Hide()
		end
		IC:GetSellInfo(spellID)
		dropText = IC:GetFactionText(spellID)
		if #IC.output > 0 then
			if dropText then
				IC.detailSellLabel:SetFormattedText("%s(%s): |cffffffff%s|r", TRADESKILL_SERVICE_LEARN, REPUTATION, dropText)
			else
				IC.detailSellLabel:SetFormattedText("%s(%s):", TRADESKILL_SERVICE_LEARN, TUTORIAL_TITLE20)
			end
			IC.detailSellLabel:Show()
			setLabelPoint(IC.detailSellLabel, getNum)
			for p, v in ipairs(IC.output) do
				dropID, dropText = v:match("^(%d+)_(.+)")
				getNum = getNum + 1
				createGetButton(getNum, dropText, tonumber(dropID), "TOPLEFT", p == 1 and IC.detailSellLabel or IC.getButtons[getNum - 1], "BOTTOMLEFT", 0, 0)
			end
			wipe(IC.output)
		elseif dropText then
			IC.detailSellLabel:SetFormattedText("%s(%s): |cffffffff%s|r", TRADESKILL_SERVICE_LEARN, REPUTATION, dropText)
			IC.detailSellLabel:Show()
			setLabelPoint(IC.detailSellLabel, getNum)
			getNum = getNum + 1
			createGetButton(getNum, "", nil, "TOPLEFT", IC.detailSellLabel, "BOTTOMLEFT", 0, 0)
		else
			IC.detailSellLabel:Hide()
		end
		dropText = IC:GetQuestText(spellID)
		if dropText then
			IC.detailQuestLabel:Show()
			setLabelPoint(IC.detailQuestLabel, getNum)
			if dropText:find(",") then
				dropText, dropID = dropText:match("(.+),(.+)")
				getNum = getNum + 1
				createGetButton(getNum, dropText, nil, "TOPLEFT", IC.detailQuestLabel, "BOTTOMLEFT", 0, 0)
				getNum = getNum + 1
				createGetButton(getNum, dropID, nil, "TOPLEFT", IC.getButtons[getNum - 1], "BOTTOMLEFT", 0, 0)
			else
				getNum = getNum + 1
				createGetButton(getNum, dropText, nil, "TOPLEFT", IC.detailQuestLabel, "BOTTOMLEFT", 0, 0)
			end
		else
			IC.detailQuestLabel:Hide()
		end
		dropText, dropID = nil
	end
	for i = getNum + 1, #IC.getButtons do
		IC.getButtons[i]:Hide()
	end
	numReagents, creatable = GetTradeSkillNumReagents(id), true
	needUpdate = nil
	if numReagents > 0 then
		setLabelPoint(TradeSkillReagentLabel, getNum)
		TradeSkillReagentLabel:Show()
		for i = 1, numReagents do
			reagentName, reagentIcon, reagentCount, reagentCountPlayer = GetTradeSkillReagentInfo(id, i)
			if reagentName and reagentIcon then
				reagentCountBank = GetItemCount(reagentName, true) - reagentCountPlayer
				if reagentCountBank > 0 then
					IC.reagentButtons[i].name:SetFormattedText("%s\n(은행: %d)", reagentName, reagentCountBank)
				else
					IC.reagentButtons[i].name:SetText(reagentName)
				end
				IC.reagentButtons[i].icon:SetTexture(reagentIcon)
				IC.reagentButtons[i].border:SetVertexColor(getQualityColor(id, i))
				reagentID = GetTradeSkillReagentItemLink(id, i)
				if reagentID then
					reagentID = reagentID:match("item:(%d+)")
					reagentID = reagentID and tonumber(reagentID)
					reagentID = checkLocation(IC:GetItemSkillID(reagentID))
					if reagentID then
						IC.reagentButtons[i].goChild:Show()
						IC.reagentButtons[i].goChild.tooltipText = ("%s|1으로;로; 바로가기"):format(reagentName)
						IC.reagentButtons[i].goChild.goto = reagentID
					else
						IC.reagentButtons[i].goChild:Hide()
					end
				else
					IC.reagentButtons[i].goChild:Hide()
				end
			else
				IC.reagentButtons[i].icon:SetTexture(reagentIcon or "Interface\\Icons\\INV_Misc_QuestionMark")
				IC.reagentButtons[i].border:SetVertexColor(0.5, 0.5, 0.5)
				IC.reagentButtons[i].name:SetText(reagentName or "미확인 아이템")
				IC.reagentButtons[i].goChild:Hide()
				creatable = nil
				needUpdate = true
			end
			if reagentCount and reagentCountPlayer then
				IC.reagentButtons[i].count:SetFormattedText("%s/%d", reagentCountPlayer > 100 and "*" or reagentCountPlayer, reagentCount)
				if reagentCount > reagentCountPlayer then
					IC.reagentButtons[i].icon:SetVertexColor(0.5, 0.5, 0.5)
					IC.reagentButtons[i].name:SetTextColor(0.58, 0.58, 0.58)
					creatable = nil
				else
					IC.reagentButtons[i].icon:SetVertexColor(1, 1, 1)
					IC.reagentButtons[i].name:SetTextColor(1, 1, 1)
				end
			else
				IC.reagentButtons[i].count:SetText(nil)
				IC.reagentButtons[i].icon:SetVertexColor(0.5, 0.5, 0.5)
				IC.reagentButtons[i].name:SetTextColor(0.58, 0.58, 0.58)
				creatable = nil
			end
			IC.reagentButtons[i]:Show()
		end
		for i = numReagents + 1, MAX_TRADE_SKILL_REAGENTS do
			IC.reagentButtons[i]:Hide()
		end
	else
		TradeSkillReagentLabel:Hide()
		for i = 1, MAX_TRADE_SKILL_REAGENTS do
			IC.reagentButtons[i]:Hide()
		end
	end
	if IC.currentSkill == IC.runeforging then

	else

	end
	TradeSkillDetailScrollFrame:Show()
	twipe(TradeSkillGuildCraftersFrame.list)
	if IsTradeSkillGuild() then
		hideCreate()
		TradeSkillViewGuildCraftersButton:Show()
		TradeSkillGuildCraftersFrame:Show()
		if TradeSkillGuildFrame.queriedSkill == TradeSkillFrame.selectedSkill then
			for _, button in pairs(IC.guildButtons) do
				button:Disable()
			end
		else
			TradeSkillGuildCraftersFrame.buttonParent:Hide()
		end
		TradeSkillViewGuildCraftersButton_OnClick()
	elseif IsTradeSkillLinked() then
		hideCreate()
		TradeSkillViewGuildCraftersButton:Hide()
		TradeSkillGuildCraftersFrame:Hide()
	else
		TradeSkillViewGuildCraftersButton:Hide()
		TradeSkillGuildCraftersFrame:Hide()
		TradeSkillCreateButton:Show()
		if altVerb then
			TradeSkillCreateAllButton:Hide()
			TradeSkillDecrementButton:Hide()
			TradeSkillInputBox:Hide()
			TradeSkillIncrementButton:Hide()
			TradeSkillCreateButton:SetText(altVerb)
		else
			TradeSkillCreateAllButton:Show()
			TradeSkillDecrementButton:Show()
			TradeSkillInputBox:Show()
			TradeSkillIncrementButton:Show()
			TradeSkillCreateButton:SetText(CREATE)
			TradeSkillInputBox:SetNumber(GetTradeskillRepeatCount())
		end
		if creatable then
			TradeSkillCreateButton:Enable()
			TradeSkillCreateAllButton:Enable()
		else
			TradeSkillCreateButton:Disable()
			TradeSkillCreateAllButton:Disable()
		end
	end
	if needUpdate then
		TradeSkillDetailScrollFrame.updateTimer = 0
		TradeSkillDetailScrollFrame:SetScript("OnUpdate", refreshDetail)
	else
		TradeSkillDetailScrollFrame:SetScript("OnUpdate", nil)
	end
end

local function sortGuildList(a, b)
	return GetGuildRecipeMember(a) < GetGuildRecipeMember(b)
end

function IC:GUILD_RECIPE_KNOWN_BY_MEMBERS()
	if TradeSkillFrame:IsShown() and IsTradeSkillGuild() and TradeSkillGuildCraftersFrame:IsShown() and TradeSkillGuildFrame.queriedSkill and TradeSkillGuildFrame.queriedSkill == TradeSkillFrame.selectedSkill then
		TradeSkillGuildCraftersFrame.num = select(3, GetGuildRecipeInfoPostQuery())
		if TradeSkillGuildCraftersFrame.num > 0 then
			twipe(TradeSkillGuildCraftersFrame.list)
			TradeSkillGuildCraftersFrame.buttonParent:Show()
			for i = 1, TradeSkillGuildCraftersFrame.num do
				if select(2, GetGuildRecipeMember(i)) then
					tinsert(TradeSkillGuildCraftersFrame.list1, i)
				else
					tinsert(TradeSkillGuildCraftersFrame.list2, i)
				end
			end
			sort(TradeSkillGuildCraftersFrame.list1, sortGuildList)
			for i = 1, #TradeSkillGuildCraftersFrame.list1 do
				tinsert(TradeSkillGuildCraftersFrame.list, TradeSkillGuildCraftersFrame.list1[i])
			end
			wipe(TradeSkillGuildCraftersFrame.list1)
			sort(TradeSkillGuildCraftersFrame.list2, sortGuildList)
			for i = 1, #TradeSkillGuildCraftersFrame.list2 do
				tinsert(TradeSkillGuildCraftersFrame.list, TradeSkillGuildCraftersFrame.list2[i])
			end
			wipe(TradeSkillGuildCraftersFrame.list2)
			TradeSkillGuildCraftersFrameScrollBar:SetValue(0)
			TradeSkillGuilCraftersFrame_Update()
		else
			TradeSkillGuildCraftersFrame.buttonParent:Hide()
		end
	else
		TradeSkillGuildFrame.queriedSkill = nil
		TradeSkillGuildCraftersFrame.buttonParent:Hide()
	end
end

local guildOffset, guildIndex

function TradeSkillGuilCraftersFrame_Update()
	guildOffset = FauxScrollFrame_GetOffset(TradeSkillGuildCraftersFrame) or 0
	for i = 1, TRADE_SKILL_GUILD_CRAFTERS_DISPLAYED do
		guildIndex = i + (guildOffset * 2)
		if TradeSkillGuildCraftersFrame.list[guildIndex] then
			IC.guildButtons[i].name, IC.guildButtons[i].online = GetGuildRecipeMember(TradeSkillGuildCraftersFrame.list[guildIndex])
			IC.guildButtons[i]:SetText(IC.guildButtons[i].name)
			if IC.guildButtons[i].online then
				IC.guildButtons[i]:Enable()
			else
				IC.guildButtons[i]:Disable()
			end
			IC.guildButtons[i]:Show()
		else
			IC.guildButtons[i]:Hide()
		end
	end
	FauxScrollFrame_Update(TradeSkillGuildCraftersFrame, ceil(TradeSkillGuildCraftersFrame.num / 2), ceil(TRADE_SKILL_GUILD_CRAFTERS_DISPLAYED / 2), TRADE_SKILL_HEIGHT, nil, nil, nil, nil, nil, nil, true)
end

IC.clearfunc[function(self)
	spellID, spellName, spellType, numAvailable, isExpanded, altVerb, minMade, maxMade, creatable = nil
	numReagents, reagentID, reagentName, reagentIcon, reagentCount, reagentCountPlayer, reagentCountBank = nil
	guildOffset, guildIndex = nil
end] = true
