local core = LibStub("AceAddon-3.0"):NewAddon("SavedInstances", "AceEvent-3.0", "AceTimer-3.0")
local L = LibStub("AceLocale-3.0"):GetLocale("SavedInstances")
local QTip = LibStub("LibQTip-1.0")
local LDB = LibStub("LibDataBroker-1.1", true)
local icon = LDB and LibStub("LibDBIcon-1.0", true)
local dataobject, db, config

-- local (optimal) references to provided functions
local date = date
local format = format
local gsub = gsub
local strfind = strfind
local strsplit = strsplit
local strsub = strsub
local strupper = strupper
local time = time
local tremove = tremove
local GetRealmName = GetRealmName
local GetNumSavedInstances = GetNumSavedInstances
local GetSavedInstanceInfo = GetSavedInstanceInfo
local SecondsToTime = SecondsToTime
local RequestRaidInfo = RequestRaidInfo
local UnitClass = UnitClass
local UnitName = UnitName

-- local (optimal) references to Blizzard's strings
local RAID_CLASS_COLORS = RAID_CLASS_COLORS
local NO_RAID_INSTANCES_SAVED = NO_RAID_INSTANCES_SAVED -- "You are not saved to any instances"
local FONTEND = FONT_COLOR_CODE_CLOSE
local GOLDFONT = NORMAL_FONT_COLOR_CODE
local YELLOWFONT = LIGHTYELLOW_FONT_COLOR_CODE
local WHITEFONT = HIGHLIGHT_FONT_COLOR_CODE
local GRAYFONT = GRAY_FONT_COLOR_CODE
local EXPANSION_NAME0 = EXPANSION_NAME0 -- "Classic"
local EXPANSION_NAME1 = EXPANSION_NAME1 -- "The Burning Crusade"
local EXPANSION_NAME2 = EXPANSION_NAME2 -- "Wrath of the Lich King"
local LFG_TYPE_DUNGEON = LFG_TYPE_DUNGEON -- "Dungeon"
local LFG_TYPE_RAID = LFG_TYPE_RAID -- "Raid"

local Indicators = {
	ICON_STAR = ICON_LIST[1] .. "16:16:0:0|t",
	ICON_CIRCLE = ICON_LIST[2] .. "16:16:0:0|t",
	ICON_DIAMOND = ICON_LIST[3] .. "16:16:0:0|t",
	ICON_TRIANGLE = ICON_LIST[4] .. "16:16:0:0|t",
	ICON_MOON = ICON_LIST[5] .. "16:16:0:0|t",
	ICON_SQUARE = ICON_LIST[6] .. "16:16:0:0|t",
	ICON_CROSS = ICON_LIST[7] .. "16:16:0:0|t",
	ICON_SKULL = ICON_LIST[8] .. "16:16:0:0|t",
	BLANK = "None",
}

local tooltip, indicatortip
local thisToon = UnitName("player") .. " - " .. GetRealmName()
local history = { }

local defaultDB = {
	DBVersion = 8,
	History = { }, -- for tracking 5 instance per hour limit
		-- key: instance string; value: time first entered
	Broker = {
		HistoryText = false,
	},
	Toons = { }, 	-- table key: "Toon - Realm"; value:
				-- Class: string
				-- AlwaysShow: boolean
	Indicators = {
		D1Indicator = "BLANK", -- indicator: ICON_*, BLANK
		D1Text = "5",
		D1Color = { 0, 0.6, 0, 1, }, -- dark green
		D1ClassColor = true,
		D2Indicator = "BLANK", -- indicator
		D2Text = "5+",
		D2Color = { 0, 1, 0, 1, }, -- green
		D2ClassColor = true,
		R1Indicator = "BLANK", -- indicator: ICON_*, BLANK
		R1Text = "10",
		R1Color = { 0.6, 0.6, 0, 1, }, -- dark yellow
		R1ClassColor = true,
		R2Indicator = "BLANK", -- indicator
		R2Text = "25",
		R2Color = { 0.6, 0, 0, 1, }, -- dark red
		R2ClassColor = true,
		R3Indicator = "BLANK", -- indicator: ICON_*, BLANK
		R3Text = "10+",
		R3Color = { 1, 1, 0, 1, }, -- yellow
		R3ClassColor = true,
		R4Indicator = "BLANK", -- indicator
		R4Text = "25+",
		R4Color = { 1, 0, 0, 1, }, -- red
		R4ClassColor = true,
	},
	Tooltip = {
		Details = false,
		NewInstanceShow = false,
		ShowCategories = true,
		ShowSoloCategory = false,
		ShowHints = true,
		ShowEncounters = false,
		ColumnStyle = "NORMAL", -- "NORMAL", "CLASS", "ALTERNATING"
		AltColumnColor = { 0.2, 0.2, 0.2, 1, }, -- grey
		RecentHistory = false,
	},
	Instances = { }, 	-- table key: "Instance name"; value:
					-- Show: boolean
					-- Order: integer
					-- Raid: boolean
					-- Expansion: integer
					-- Encounters: table integer = "Encounter name"
					-- table key: "Toon - Realm"; value:
						-- table key: "Difficulty"; value:
							-- ID: integer
							-- Expires: integer
	Categories = {
		D0 = { Name = EXPANSION_NAME0 .. ": " .. LFG_TYPE_DUNGEON, Order = 1 },
		R0 = { Name = EXPANSION_NAME0 .. ": " .. LFG_TYPE_RAID, Order = 2 },
		D1 = { Name = EXPANSION_NAME1 .. ": " .. LFG_TYPE_DUNGEON, Order = 3 },
		R1 = { Name = EXPANSION_NAME1 .. ": " .. LFG_TYPE_RAID, Order = 4 },
		D2 = { Name = EXPANSION_NAME2 .. ": " .. LFG_TYPE_DUNGEON, Order = 5 },
		R2 = { Name = EXPANSION_NAME2 .. ": " .. LFG_TYPE_RAID, Order = 6 },
	},
	MinimapIcon = { },
	Lockouts = {	-- table key: lockout ID; value:
						-- Name: string
						-- Members: table "Toon name" = "Class"
						-- Encounters: integer = boolean
						-- Note: string
	},
}

-- general helper functions below

local function ColorCodeOpen(color)
	return format("|c%02x%02x%02x%02x", math.floor(color[4] * 255), math.floor(color[1] * 255), math.floor(color[2] * 255), math.floor(color[3] * 255))
end

local function ClassColorise(class, targetstring)
	local RAID_CLASS_COLORS = CUSTOM_CLASS_COLORS or RAID_CLASS_COLORS
	local color = {
		RAID_CLASS_COLORS[class].r,
		RAID_CLASS_COLORS[class].g,
		RAID_CLASS_COLORS[class].b,
		1,
	}
	return ColorCodeOpen(color) .. targetstring .. FONTEND
end

local function TableLen(table)
	local i = 0
	for _, _ in pairs(table) do
		i = i + 1
	end
	return i
end

-- local addon functions below

local function InstanceCategory(instance)
	if not instance then return nil end
	local instance = core.db.Instances[instance]
	return ((instance.Raid and "R") or ((not instance.Raid) and "D")) .. instance.Expansion
end

local function InstancesInCategory(targetcategory)
	-- returns a table of the form { "instance1", "instance2", ... }
	if (not targetcategory) then return { } end
	local list = { }
	for instance, _ in pairs(core.db.Instances) do
		if InstanceCategory(instance) == targetcategory then
			list[#list+1] = instance
		end
	end
	return list
end

local function CategorySize(category)
	if not category then return nil end
	local i = 0
	for instance, _ in pairs(core.db.Instances) do
		if category == InstanceCategory(instance) then
			i = i + 1
		end
	end
	return i
end

local function OrderedInstances(category)
	-- returns a table of the form { "instance1", "instance2", ... }
	-- adjusts the Order value for each instance in the category
	if (not category) then return { } end
	local orderedlist = { }
	local instances = InstancesInCategory(category)
	while #orderedlist < CategorySize(category) and #instances > 0 do
		local nextinstance
		local nextinstanceindex
		for i, instance in ipairs(instances) do
			nextinstance = nextinstance or instance
			if core.db.Instances[instance].Order <= core.db.Instances[nextinstance].Order then
				nextinstance = instance
				nextinstanceindex = i
			end
		end
		orderedlist[#orderedlist+1] = nextinstance
		tremove(instances, nextinstanceindex)
	end
	for i, instance in ipairs(orderedlist) do
		core.db.Instances[instance].Order = i
	end
	return orderedlist
end


local function OrderedCategories()
	-- returns a table of the form { "instance1", "instance2", ... }
	-- adjusts the Order value for each category
	local orderedlist = { }
	local categories = { }
	for category, v in pairs(core.db.Categories) do
		categories[#categories+1] = category
	end
	while #orderedlist < TableLen(core.db.Categories) and #categories > 0 do
		local nextcategory
		local nextinstanceindex
		for i, category in ipairs(categories) do
			nextcategory = nextcategory or category
			if core.db.Categories[category].Order <= core.db.Categories[nextcategory].Order then
				nextcategory = category
				nextcategoryindex = i
			end
		end
		orderedlist[#orderedlist+1] = nextcategory
		tremove(categories, nextcategoryindex)
	end
	for i, category in ipairs(orderedlist) do
		core.db.Categories[category].Order = i
	end
	return orderedlist
end

local function DifficultyString(instance, diff, toon)
	local instance = core.db.Instances[instance]
	local setting = ((instance.Raid and "R") or ((not instance.Raid) and "D")) .. tostring(diff)
	local prefs = core.db.Indicators
	if prefs[setting .. "ClassColor"] then
		local RAID_CLASS_COLORS = CUSTOM_CLASS_COLORS or RAID_CLASS_COLORS
		color = {
		RAID_CLASS_COLORS[core.db.Toons[toon].Class].r,
		RAID_CLASS_COLORS[core.db.Toons[toon].Class].g,
		RAID_CLASS_COLORS[core.db.Toons[toon].Class].b,
		1,
	}
	else
		color = prefs[setting.."Color"]
	end
	if not strfind(prefs[setting.."Text"], "ICON", 1, true) then
		return ColorCodeOpen(color) .. prefs[setting.."Text"] .. FONTEND
	end
	local iconstring
	if prefs[setting.."Indicator"] == "BLANK" then
		iconstring = ""
	else
		iconstring = FONTEND .. Indicators[prefs[setting.."Indicator"]] .. ColorCodeOpen(color)
	end
	return ColorCodeOpen(color) .. gsub(prefs[setting.."Text"], "ICON", iconstring) .. FONTEND
end

local function MaintainInstanceDB()
	for instance, i in pairs(db.Instances) do
		i.Raid = i.Raid or false
		i.Expansion = i.Expansion or 0
		i.Order = i.Order or 1
		i.Show = i.Show or db.Tooltip.NewInstanceShow
		i.Encounters = i.Encounters or { }
		for toon, t in pairs(db.Toons) do
			if i[toon] then
				for difficulty, d in pairs(i[toon]) do
					if d.Expires < time() then
						i[toon][difficulty] = nil
						db.Lockouts[d.ID] = nil
					else
						db.Lockouts[d.ID] = db.Lockouts[d.ID] or { }
						db.Lockouts[d.ID].Members = db.Lockouts[d.ID].Members or { }
						db.Lockouts[d.ID].Members[strsplit(' ', toon)] = db.Lockouts[d.ID].Members[strsplit(' ', toon)] or { Class = t.Class }
						db.Lockouts[d.ID].Name = instance
						db.Lockouts[d.ID].Encounters = db.Lockouts[d.ID].Encounters or { }
						for e, encounter in ipairs(i.Encounters) do
							db.Lockouts[d.ID].Encounters[e] = db.Lockouts[d.ID].Encounters[e] or false
						end
					end
				end
				if TableLen(i[toon]) == 0 then
					i[toon] = nil
				end
			end
		end
	end
end

local function ShowIndicatorTooltip(cell, arg, ...)
	local instance = arg[1]
	local toon = arg[2]
	local diff = arg[3]
	if not instance or not toon or not diff then return end
	indicatortip = QTip:Acquire("SavedInstancesIndicatorTooltip", 2, "LEFT", "RIGHT")
	indicatortip:Clear()
	indicatortip:SetHeaderFont(tooltip:GetHeaderFont())
	local thisinstance = core.db.Instances[instance]
	local id = thisinstance[toon][diff].ID
	local nameline, _ = indicatortip:AddHeader()
	indicatortip:SetCell(nameline, 1, DifficultyString(instance, diff, toon) .. " " .. GOLDFONT .. instance .. FONTEND, indicatortip:GetHeaderFont(), "LEFT", 2)
	indicatortip:AddHeader(ClassColorise(core.db.Toons[toon].Class, strsplit(' ', toon)), id)
	indicatortip:AddLine(YELLOWFONT .. L["Time Left"] .. ":" .. FONTEND, SecondsToTime(thisinstance[toon][diff].Expires - time()))
	if db.Lockouts[id].Note and db.Lockouts[id].Note ~= "" then
		local noteline, _ = indicatortip:AddLine()
		indicatortip:SetCell(noteline, 1, WHITEFONT .. db.Lockouts[id].Note .. FONTEND, "LEFT", 2)
	end
	if db.Tooltip.ShowEncounters and TableLen(thisinstance.Encounters) > 0 then
		for i, encounter in ipairs(thisinstance.Encounters) do
			local encline, _ = indicatortip:AddLine()
			local color = GRAYFONT
			if db.Lockouts[id].Encounters[i] then
				color = GOLDFONT
			end
			indicatortip:SetCell(encline, 1, color .. encounter .. FONTEND, "LEFT", 2)
		end
	end
	indicatortip:SetAutoHideDelay(0.1, tooltip)
	indicatortip:SmartAnchorTo(tooltip)
	indicatortip:Show()
end

local function UpdateLDBTextMode()
	if db.Broker.HistoryText then
		dataobject.type = "data source"
		core:ScheduleRepeatingTimer("UpdateLDBText", 5, nil)
	else
		dataobject.type = "launcher"
		dataobject.text = "SavedInstances"
		core:CancelAllTimers()
	end
end

-- global addon code below

function core:OnInitialize()
	core.defaultDB = defaultDB
	SavedInstancesDB = SavedInstancesDB or defaultDB
	-- begin backwards compatibility
	if not SavedInstancesDB.DBVersion then
		SavedInstancesDB = defaultDB
	end
	if SavedInstancesDB.DBVersion == 4 then
		SavedInstancesDB.DBVersion = 5
		SavedInstancesDB.Indicators.UnsavedIndicator = nil
		SavedInstancesDB.Indicators.UnsavedText = nil
		SavedInstancesDB.Indicators.UnsavedColor = nil
		for toon, a in pairs(SavedInstancesDB.Toons) do
			a.Class = strupper(gsub(a.Class, " ", ""))
			a.NumSaved = nil
		end
	end
	if SavedInstancesDB.DBVersion == 5 then
		SavedInstancesDB.DBVersion = 6
		SavedInstancesDB.Indicators = defaultDB.Indicators
		SavedInstancesDB.Categories = defaultDB.Categories
		SavedInstancesDB.Tooltip.ShowCategories = true
		SavedInstancesDB.Tooltip.ShowSoloCategory = false
		for instance, a in pairs(SavedInstancesDB.Instances) do
			for toon, b in pairs(SavedInstancesDB.Toons) do
				if a[toon] then
					if a[toon]["Normal"] then
						a[toon][1] = a[toon]["Normal"]
						a[toon]["Normal"] = nil
					end
					if a[toon]["Heroic"] then
						a[toon][2] = a[toon]["Heroic"]
						a[toon]["Heroic"] = nil
					end
				end
			end
		end
	end
	if SavedInstancesDB.DBVersion == 6 then
		SavedInstancesDB.DBVersion = 7
		SavedInstancesDB.Tooltip.ShowHints = true
	end
	if SavedInstancesDB.DBVersion == 7 then
		SavedInstancesDB.DBVersion = 8
		SavedInstancesDB.Tooltip = defaultDB.Tooltip
		SavedInstancesDB.Broker = defaultDB.Broker
	end
	if SavedInstancesDB.DBVersion ~= 8 then
		SavedInstancesDB = defaultDB
	end
	-- end backwards compatibilty
	db = db or SavedInstancesDB
	self.db = db
	config = core:GetModule("Config")
	self.config = config
	db.Toons[thisToon] = db.Toons[thisToon] or { }
	db.Toons[thisToon].Class = db.Toons[thisToon].Class or select(2, UnitClass("player"))
	db.Toons[thisToon].AlwaysShow = db.Toons[thisToon].AlwaysShow or false
	db.Lockouts = db.Lockouts or { }
	RequestRaidInfo()
	dataobject = LDB and LDB:NewDataObject("SavedInstances", {
		text = "",
		type = "launcher",
		icon = "Interface\\Addons\\SavedInstances\\icon.tga",
		OnEnter = function(frame)
			core:ShowTooltip(frame)
		end,
		OnClick = function(frame, button)
			if button == "LeftButton" then
				ToggleFriendsFrame(5) -- open Blizzard Raid window
				RaidInfoFrame:Show()
			else
				config:ShowConfig()
			end
		end
	})
	self.dataobject = dataobject
	if icon then
		icon:Register("SavedInstances", dataobject, db.MinimapIcon)
	end
	UpdateLDBTextMode()
end

function core:OnEnable()
	self:RegisterEvent("UPDATE_INSTANCE_INFO", "Refresh")
	self:RegisterEvent("RAID_INSTANCE_WELCOME", RequestRaidInfo)
	self:RegisterEvent("CHAT_MSG_SYSTEM", "CheckSystemMessage")
end

function core:OnDisable()
	self:UnregisterEvent("UPDATE_INSTANCE_INFO")
	self:UnregisterEvent("RAID_INSTANCE_WELCOME")
	self:UnregisterEvent("CHAT_MSG_SYSTEM")
end

function core:CheckSystemMessage()
	if tostring(arg1) == INSTANCE_SAVED then
		RequestRaidInfo()
	end
end

function core:Refresh()
	MaintainInstanceDB()
	local numsaved = GetNumSavedInstances()
	if numsaved > 0 then
		for i = 1, numsaved do
			local name, id, expires, diff, locked, extended, mostsig, raid, players, diffname = GetSavedInstanceInfo(i)
			core.db.Instances[name] = core.db.Instances[name] or { }
			local instance = core.db.Instances[name]
			instance.Raid = instance.Raid or raid
			instance.Expansion = instance.Expansion or 0
			instance.Order = instance.Order or 1
			instance.Show = instance.Show or core.db.Tooltip.NewInstanceShow
			if locked then
				instance[thisToon] = instance[thisToon] or { }
				instance[thisToon][diff] = {
					ID = id,
					Expires = expires + time()
				}
			end
		end
	end
end

function core:ShowTooltip(anchorframe)
	if tooltip and tooltip:IsShown() then return end
	tooltip = QTip:Acquire("SavedInstancesTooltip", 1, "LEFT")
	tooltip:Clear()
	local hFont = tooltip:GetHeaderFont()
	local hFontPath, hFontSize
	hFontPath, hFontSize, _ = hFont:GetFont()
	hFont:SetFont(hFontPath, hFontSize, "OUTLINE")
	tooltip:SetHeaderFont(hFont)
	local headLine, headCol = tooltip:AddHeader(GOLDFONT .. "SavedInstances" .. FONTEND)
	MaintainInstanceDB()
	if columns then columns = nil end
	local columns = { }
	-- allocating columns for characters
	if core.db.Toons[thisToon].AlwaysShow then
		for diff = 1, 4 do
			columns[thisToon..diff] = columns[thisToon..diff] or tooltip:AddColumn("CENTER")
		end
	end
	for toon, t in pairs(core.db.Toons) do
		if core.db.Toons[toon].AlwaysShow then
			for diff = 1, 4 do
				columns[toon..diff] = columns[toon..diff] or tooltip:AddColumn("CENTER")
			end
		end
	end
	-- determining how many instances will be displayed per category
	local categorysize = { } -- remember the number of instances to be shown for each category
	local instancesaved = { } -- remember if each instance has been saved or not (boolean)
	local doseparator = false -- use this to determine whether to insert spaces or not
	for _, category in ipairs(OrderedCategories()) do
		categorysize[category] = 0
		for _, instance in ipairs(OrderedInstances(category)) do
			for toon, t in pairs(core.db.Toons) do
				for diff = 1, 4 do
					if core.db.Instances[instance][toon] and core.db.Instances[instance][toon][diff] then
						instancesaved[instance] = true
						categorysize[category] = categorysize[category] + 1
					elseif core.db.Instances[instance].Show then
						categorysize[category] = categorysize[category] + 1
					end
				end
			end
		end
	end
	local categories = 0
	-- determining how many categories have instances that will be shown
	if core.db.Tooltip.ShowCategories then
		for category, size in pairs(categorysize) do
			if size > 0 then
				categories = categories + 1
			end
		end
	end
	-- allocating tooltip space for instances, categories, and space between categories
	local categoryrow = { } -- remember where each category heading goes
	local instancerow = { } -- remember where each instance goes
	local firstcategory = true -- use this to skip spacing before the first category
	for _, category in ipairs(OrderedCategories()) do
		if categorysize[category] > 0 then
			if not firstcategory then
				tooltip:AddSeparator(6,0,0,0,0)
			end
			if (categories > 1 or core.db.Tooltip.ShowSoloCategory) and (categorysize[category] > 0) then
				categoryrow[category], _ = tooltip:AddLine()

			end
			for _, instance in ipairs(OrderedInstances(category)) do
				for toon, t in pairs(core.db.Toons) do
					for diff = 1, 4 do
						if core.db.Instances[instance][toon] and core.db.Instances[instance][toon][diff] then
							instancerow[instance] = instancerow[instance] or tooltip:AddLine()
							for diff = 1, 4 do
								columns[toon..diff] = columns[toon..diff] or tooltip:AddColumn("CENTER")
							end
						elseif core.db.Instances[instance].Show then
							instancerow[instance] = instancerow[instance] or tooltip:AddLine()
						end
					end
				end
			end
			firstcategory = false
		end
	end
	-- now printing instance data
	for instance, row in pairs(instancerow) do
		if instancesaved[instance] then
			tooltip:SetCell(instancerow[instance], 1, GOLDFONT .. instance .. FONTEND)
			for toon, t in pairs(core.db.Toons) do
				if core.db.Instances[instance][toon] then
					for diff = 1, 4 do
						local save = core.db.Instances[instance][toon][diff]
						if save ~= nil then
							tooltip:SetCell(instancerow[instance], columns[toon..diff], DifficultyString(instance, diff, toon))
							tooltip:SetCellScript(instancerow[instance], columns[toon..diff], "OnEnter", ShowIndicatorTooltip, {instance, toon, diff})
						else
							tooltip:SetCell(instancerow[instance], columns[toon..diff], "")
						end
					end
				end
			end
		elseif (not instancesaved[instance]) and (core.db.Instances[instance].Show) then
			tooltip:SetCell(instancerow[instance], 1, GRAYFONT .. instance .. FONTEND)
		end
	end
	-- toon names
	for toondiff, col in pairs(columns) do
		local toon = strsub(toondiff, 1, #toondiff-1)
		local diff = strsub(toondiff, #toondiff, #toondiff)
		if diff == "1" then
			tooltip:SetCell(headLine, col, ClassColorise(core.db.Toons[toon].Class, select(1, strsplit(" - ", toon))), tooltip:GetHeaderFont(), "CENTER", 4)
		end
	end 
	-- we now know enough to put in the category names where necessary
	if core.db.Tooltip.ShowCategories then
		for category, row in pairs(categoryrow) do
			if (categories > 1 or core.db.Tooltip.ShowSoloCategory) and (categorysize[category] > 0) then
				tooltip:SetCell(categoryrow[category], 1, YELLOWFONT .. core.db.Categories[category].Name .. FONTEND, "LEFT", tooltip:GetColumnCount())
			end
		end
	end
	-- finishing up, with hints
	if TableLen(instancerow) == 0 then
		local noneLine = tooltip:AddLine()
		tooltip:SetCell(noneLine, 1, GRAYFONT .. NO_RAID_INSTANCES_SAVED .. FONTEND, "LEFT", tooltip:GetColumnCount())
	end
	if core.db.Tooltip.ShowHints then
		tooltip:AddSeparator(8,0,0,0,0)
		local hintLine, hintCol
		hintLine, hintCol = tooltip:AddLine()
		tooltip:SetCell(hintLine, hintCol, L["|cffffff00Left-click|r to show Blizzard's Raid Information"], "LEFT", tooltip:GetColumnCount())
		hintLine, hintCol = tooltip:AddLine()
		tooltip:SetCell(hintLine, hintCol, L["|cffffff00Right-click|r to configure SavedInstances"], "LEFT", tooltip:GetColumnCount())
		hintLine, hintCol = tooltip:AddLine()
		tooltip:SetCell(hintLine, hintCol, L["Hover mouse on indicator for details"], "LEFT", tooltip:GetColumnCount())
	end
	-- tooltip column colours
	if core.db.Tooltip.ColumnStyle == "CLASS" then
		for toondiff, col in pairs(columns) do
			local toon = strsub(toondiff, 1, #toondiff-1)
			local diff = strsub(toondiff, #toondiff, #toondiff)
			local color = RAID_CLASS_COLORS[core.db.Toons[toon].Class]
			tooltip:SetColumnColor(col, color.r, color.g, color.b)
		end 
	end						
	tooltip:SetAutoHideDelay(0.1, anchorframe)
	tooltip:SmartAnchorTo(anchorframe)
	tooltip:Show()
end

function core:UpdateLDBText()
	if db.History and TableLen(db.History) >= 2 then
		-- do the stuff :)
		-- SavedInstances.launcher.text = format(L["%s instances"], number)
		-- SavedInstances.launcher.text = format(L["%s instances"], number)
	else
		dataobject.text = ""
	end	
end
