-----------------------------
--     Blue Craft Info     --
-- 알렉스트라자 무서운독감 --
--       (InTheBlue)       --
-----------------------------

-- 기본 변수 선언
BlueCraftInfo = AceLibrary("AceAddon-2.0"):new("AceEvent-2.0", "AceConsole-2.0", "AceDB-2.0", "FuBarPlugin-2.0")
local self = BlueCraftInfo
local Tablet = AceLibrary("Tablet-2.0")
local TipHooker = AceLibrary("TipHooker-1.0")
local IDTable = {}
local tooltip = CreateFrame("GameTooltip", "BlueCraftInfoTooltip", UIParent, "GameTooltipTemplate")
local cacheCount = 0
self.title = "BlueCraftInfo"
self.version = "1.5"
self.website = GetAddOnMetadata("BlueCraftInfo", "X-Website")
self.hasIcon = "Interface\\Icons\\INV_Misc_Coin_01"
self.hideWithoutStandby = true
self.overrideMenu = true
self.blizzardTooltip = true
self.defaultMinimapPosition = 100
self.skillNameKR = { "가죽세공", "연금술", "대장기술", "기계공학", "재봉술", "보석세공", "마법부여", "채광", "요리", "응급치료", "독" }
self.skillNameEN = { "Leatherworking", "Alchemy", "Blacksmithing", "Engineering", "Tailoring", "Jewelcrafting", "Enchanting", "Smelting", "Cooking", "FirstAid", "Poisons" }
BINDING_HEADER_BLUECRAFTINFO = "Blue Craft Info"
BINDING_NAME_BLUECRAFTINFO_TOGGLE = "UI창 열기/닫기"

local defaultOption = {
	position = { isSet = false, x = 0, y = 0 },
	backdrop = { r = 0, g = 0, b = 0.2, a = 0.8 },
	list = 1, setid = 2, reagent = true, recipe = true, drop = true
}

local options = {
	type = "group",
	icon = self.hasIcon,
	args = {
		ui = {
			type = "execute",
			name = "열기/닫기",
			desc = "UI창을 열고 닫습니다.",
			order = 1,
			func = function() self:OnClick() AceLibrary("Dewdrop-2.0"):Close() end,
		},
		backdrop = {
			type = "color",
			name = "배경 색상",
			desc = "UI창의 배경 색상을 설정합니다.",
			order = 2,
			get = function() return self.db.profile.backdrop.r, self.db.profile.backdrop.g, self.db.profile.backdrop.b, BlueCraftInfo.db.profile.backdrop.a end,
			set = function(r, g, b, a)
				self.db.profile.backdrop = { r = r, g = g, b = b, a = a }
				if BlueCraftInfoUI then
					BlueCraftInfoUI:SetBackdropColor()
				end
			end,
			hasAlpha = true,
		},
		reagent = {
			type = "toggle",
			name = "재료 사용처 표시",
			desc = "재료 아이템 툴팁에 전문기술 사용처를 표시합니다.",
			order = 3,
			get = function() return self.db.profile.reagent end,
			set = function() self.db.profile.reagent = not self.db.profile.reagent end,
		},
		recipe = {
			type = "toggle",
			name = "제작 아이템에 재료 표시",
			desc = "전문 기술로 제작된 아이템 툴팁에 재료를 표시합니다.",
			order = 4,
			get = function() return self.db.profile.recipe end,
			set = function() self.db.profile.recipe = not self.db.profile.recipe end,
		},
		drop = {
			type = "toggle",
			name = "제작 아이템에 도안 획득처 표시",
			desc = "전문 기술로 제작된 아이템 툴팁에 도안 획득처를 표시합니다.",
			order = 5,
			get = function() return self.db.profile.drop end,
			set = function() self.db.profile.drop = not self.db.profile.drop end,
		},
		menu = {
			type = "group",
			name = "메뉴",
			desc = "미니맵 아이콘 및 푸바 메뉴를 설정합니다.",
			args = AceLibrary("FuBarPlugin-2.0"):GetAceOptionsDataTable(self),
			order = 100,
		}
	},
}

BlueCraftInfo.OnMenuRequest = options

-- 로컬 함수 선언
local strfind, strsub, strsplit, strjoin, strlen, gsub, unpack = strfind, strsub, strsplit, strjoin, strlen, gsub, unpack
local type, tonumber, abs, mod = type, tonumber, abs, mod

function Comp36(n)
	if n then
		local p, v, s = "", ""
		if n < 0 then
			p = "-"
			n = abs(n)
		end
		while n > 0 do
			s = mod(n, 36)
			v = strsub("0123456789abcdefghijklmnopqrstuvwxyz", s + 1, s + 1)..v
			n = (n - s) / 36
		end
		return p..v
	else
		return nil
	end
end

function Uncomp36(n)
	return n and tonumber(n, 36) or nil
end

function gsubs(text, gsubdata, text2)
	if text == nil or text2 == nil then
		return
	end
	if text and gsubdata and text2 then
		if type(text2) == "table" then
			for i = 1, #(gsubdata) do
				text = gsub(text, gsubdata[i], text2[i])
			end
			return text
		else
			for i = 1, #(gsubdata) do
				text = gsub(text, gsubdata[i], text2)
			end
			return text
		end
	end
	return nil
end

function sfind(text, pattern, init, plain)
	if text and pattern then
		return strfind(text, pattern, init, plain)
	end
	return nil
end

function BlueCraftInfo:OnInitialize()
	self:RegisterDB("BlueCraftInfoSave")
	self:RegisterDefaults("profile", defaultOption)
	self:RegisterChatCommand({ "/bci"}, options)
	self.cache = {}
	self.Recipe = "/"..self.Recipe.."/"
	self:CreateIDTable()
end

function BlueCraftInfo:OnEnable()
	TipHooker:Hook(self.ProcessTooltip, "item")
end

function BlueCraftInfo:OnDisable()
	TipHooker:Unhook(self.ProcessTooltip, "item")
end

do

function BlueCraftInfo.ProcessTooltip(tooltip, name, link)
	local _, _, itemID = strfind(link, "item:(%d+):")
	if itemID then
		itemID = tonumber(itemID)
		if self.db.profile.drop or self.db.profile.recipe or self.db.profile.reagent then
			if self.cache[itemID] == nil then
				local ri1, ri2, ri3 = self:GetRecipe2Item(itemID)
				local ri4 = self:GetReagentItemInfo(itemID)
				if ri1 or ri2 or ri3 or ri4 then
					self.cache[itemID] = { ri1, ri2, ri3, ri4 }
				else
					self.cache[itemID] = 1
				end
			end
			if type(self.cache[itemID]) == "table" then
				if self.db.profile.drop and self.cache[itemID][1] then
					tooltip:AddLine("|cffffaaff도안: "..self.cache[itemID][1])
				end
				if self.db.profile.reagent and self.cache[itemID][4] then
					tooltip:AddLine("|cff1e90ff사용: |r"..self.cache[itemID][4], 1, 1, 1, 1)
				end
				if self.db.profile.recipe and self.cache[itemID][2] then
					tooltip:AddLine("|cff40a940"..self.skillNameKR[self.cache[itemID][3]]..": |r"..self.cache[itemID][2], 1, 1, 1, 1)
				end
			end
		end
	end
	tooltip:Show()
end

function BlueCraftInfo:GetRecipe2Item(itemID)
	if itemID then
		local id36, s, db, id, tradeskill, getrecipe
		id36 = (type(itemID) == "string") and itemID or Comp36(itemID)
		local loc1, loc2 = sfind(IDTable, "/"..id36..":")
		if loc1 then
			loc2 = loc2 + 1
			loc1 = sfind(IDTable, "/", loc2)
			db = strsub(IDTable, loc2, loc1 - 1)
			id, tradeskill, getrecipe = strsplit("_", db)
			return self:GetRecipeDrop(getrecipe), self:GetReagent(Uncomp36(id)), tonumber(tradeskill)
		end
	end
	return nil
end

function BlueCraftInfo:GetItem2Recipe(recipeID)
	if recipeID then
		local id36 = (type(recipeID) == "string") and recipeID or Comp36(recipeID)
		local loc1, loc2 = sfind(IDTable, ":"..id36.."_")
		if loc1 then
			local db = strsub(IDTable, loc1 - 4, loc1 - 1)
			loc2 = sfind(db, "/")
			db = loc2 and strsub(db, loc2 + 1) or db
			return Uncomp36(db)
		end
	end
	return nil
end

function BlueCraftInfo:GetRecipeDrop(dropID)
	if dropID then
		local loc1, loc2 = strfind(self.Recipe, "/"..dropID..":")
		if loc1 then
			loc2 = loc2 + 1
			loc1 = strfind(self.Recipe, "/", loc2)
			local getrecipe = strsub(self.Recipe, loc2, loc1 - 1)
			for p, v in pairs(self.NPCS) do
				getrecipe = gsub(getrecipe, p, v)
			end
			return gsubs(getrecipe, { "u", "w", "r", "d", "z", "n", "_", "-확", "-매", "-우", "-약" }, { "|cffFF0000", "|cffFFFFFF", "|cffFF7DB4", "|cff7DF4B2", "|cffBFEFFF", "|cffFFFFA4", "\n ", "(확고)", "(매우우호)", "(우호)", "(약간우호)" })
		end
	end
	return nil
end

function BlueCraftInfo:GetReagent(recipeID)
	BlueCraftInfoTooltip:SetOwner(UIParent, "ANCHOR_NONE")
	BlueCraftInfoTooltip:ClearLines()
	local tp1, tp2 = BlueCraftInfoTooltipTextLeft1, BlueCraftInfoTooltipTextLeft2
	tp1:SetText()
	tp2:SetText()
	BlueCraftInfoTooltip:SetHyperlink("enchant:"..recipeID)
	BlueCraftInfoTooltip:Show()
	local text1 = tp1:GetText()
	local text2 = tp2:GetText()
	local reagent = (sfind(text2, "^재료:") and text2) or (sfind(text1, "^재료:") and text1) or nil
	BlueCraftInfoTooltip:Hide()
	return reagent and gsubs(reagent, { "재료: ", strchar(124).."cffffffff", strchar(124).."cffff2020", strchar(124).."r", strchar(124).."n" }, "") or nil
end

function BlueCraftInfo:GetReagentItemInfo(itemID)
	if itemID then
		itemID = Comp36(itemID)
		local loc1, loc2 = strfind(self.Reagent, "/"..itemID..":")
		if loc1 then
			loc2 = loc2 + 1
			loc1 = strfind(self.Reagent, "/", loc2)
			local n = Uncomp36(strsub(self.Reagent, loc2, loc1 - 1))
			local used, v, s = {}, ""
			while n > 0 do
				s = mod(n, 2)
				v = v..s
				n = (n - s) / 2
			end
			for i = 1, strlen(v) do
				if strsub(v, i, i) == "1" then
					used[#(used) + 1] = self.skillNameKR[i]
				end
			end
			return strjoin(", ", unpack(used))
		end
	end
	return nil
end

end

function BlueCraftInfo:OnClick()
	if not(self.loadedUI) then
		self.loadedUI = LoadAddOn("BlueCraftInfoUI")
	end
	BlueCraftInfoUI:FrameToggle()
end

function BlueCraftInfo:OnTooltipUpdate()
	GameTooltip:AddLine("BlueCraftInfo")
	GameTooltip:AddLine(self.website, 1, 1, 1)
	GameTooltip:AddLine("좌클릭: UI창 토글", 0.2, 1, 0.2)
	GameTooltip:AddLine("우클릭: 설정", 0.2, 1, 0.2)
end

function BlueCraftInfo:CreateIDTable()
	IDTable = "/"
	local db, ts, iid, tail
	local ln = { ["Leatherworking"] = 1, ["Alchemy"] = 2, ["Blacksmithing"] = 3, ["Engineering"] = 4, ["Tailoring"] = 5, ["Jewelcrafting"] = 6, ["Enchanting"] = 7, ["Smelting"] = 8, ["Cooking"] = 9, ["FirstAid"] = 10, ["Poisons"] = 11 }
	for p, v in pairs(self.Data) do
		for i = 1, #(v) do
			db = { strsplit("/", v[i][2]) }
			for k = 1, #(db or {}) do
				ts = { strsplit("|", db[k]) }
				if ts and ts[1] and ts[2] and ts[4] and ts[4] ~= "0" and not(strfind(ts[1], "(.+)을 (.+)로")) and not(strfind(ts[1], "(.+)를 (.+)로")) and ts[1] ~= "자연의 불꽃" and ts[1] ~= "공허의 조각_3" and ts[1] ~= "무지갯빛 작은 결정_3" and ts[1] ~= "무지갯빛 큰 결정_3" and ts[1] ~= "마력 변환_3" then
					iid = strsplit("_", ts[4])
					tail = ts[5] and ("_"..ts[5].."/") or "/"
					IDTable = IDTable..iid..":"..ts[2].."_"..ln[p]..tail
				end
			end
		end
	end
	collectgarbage()
end