local name, ns = ...
local debug = ns.debug

local Addon = _G[name]
local tq = LibStub("LibTalentQuery-1.0")

local L = LibStub("AceLocale-3.0"):GetLocale(name)

local MIN_TIME_UNTIL_RESCAN = 60
local lastscan = {}

local talentSpecs = {}
local talentSpecNames = {}
local talentSpecIcons = {}
local function updatetalent(event, name, realm)
	lastscan[name] = GetTime()
	local name = name .. (realm or "")
	local data = talentSpecs[name] or {[1] = {}, [2] = {}, [3] = {},}
	local specName = { NONE, 0 }
	local isInspect = name ~= UnitName("player")
	for i = 1, 3 do
		local active = GetActiveTalentGroup(isInspect)
		local _, name, _, icon, points = GetTalentTabInfo(i, isInspect, false, active)
		data[i][1] = name
		data[i][2] = points
		data[i][3] = icon
		if points > specName[2] then
			specName[1] = name
			specName[2] = points
			specName[3] = icon
		elseif points == specName[2] then
			specName[1] = "Hybrid"
		end
	end
	talentSpecs[name] = data
	talentSpecNames[name] = specName[1]
	talentSpecIcons[name] = specName[3]
end
tq.RegisterCallback(Addon, "TalentQuery_Ready", updatetalent)

local function query(unit)
	local name = UnitName(unit)
	if not name then return end
	if not CanInspect(unit) or UnitLevel(unit) < 10 then return end
	local curTime = GetTime()
	local last = lastscan[name]
	if last and (curTime - last) < MIN_TIME_UNTIL_RESCAN then
		debug("skip rescan. next update will be in: ", MIN_TIME_UNTIL_RESCAN - curTime + last)
		return
	end
	tq:Query(unit)
end

local function TalentSpec(unit)
	if not UnitIsPlayer(unit) then
		return
	end
	local name = UnitName(unit)
	if not name then return end
	query(unit)
	local spec = talentSpecs[name]
	if spec then
		return ("%d/%d/%d"):format(spec[1][2], spec[2][2], spec[3][2])
	else
		if CanInspect(unit) and UnitLevel(unit) >= 10 then
			return L["Scanning Talents..."]
		end
	end
end
Addon.ScriptEnv.TalentSpec = TalentSpec

local function TalentSpecName(unit)
	if not UnitIsPlayer(unit) then
		return
	end
	local name = UnitName(unit)
	if not name then return end
	query(unit)
	return talentSpecNames[name]
end
Addon.ScriptEnv.TalentSpecName = TalentSpecName

local function TalentSpecIcon(unit)
	if not UnitIsPlayer(unit) then
		return
	end
	local name = UnitName(unit)
	if not name then return end
	query(unit)
	return talentSpecIcons[name]
end
Addon.ScriptEnv.TalentSpecIcon = TalentSpecIcon
