local VERSION = tonumber(("$Revision: 31545 $"):match("%d+"))

local QuestsFu = QuestsFu
local QuestsFu_Comments = QuestsFu:NewModule("Comments", "AceHook-2.1", "AceEvent-2.0", "AceConsole-2.0")
if QuestsFu.revision < VERSION then
	QuestsFu.version = "r" .. VERSION
	QuestsFu.revision = VERSION
	QuestsFu.date = ("$Date: 2007-04-01 10:25:17 -0400 (Sun, 01 Apr 2007) $"):match("%d%d%d%d%-%d%d%-%d%d")
end

local tablet = AceLibrary("Tablet-2.0")
local quixote = AceLibrary("Quixote-1.0")
local dewdrop = AceLibrary("Dewdrop-2.0")

local L = AceLibrary("AceLocale-2.2"):new("QuestsFu_Comments")
L:RegisterTranslations("enUS", function() return {
	["Comments"] = true,
	["Display quest comments."] = true,
} end)

L:RegisterTranslations("deDE", function() return {
	["Comments"] = "Kommentare",
	["Display quest comments."] = "Anzeigen von Quest Kommentaren.",
} end)

function QuestsFu_Comments:OnInitialize()
	self.db = QuestsFu:AcquireDBNamespace("Comments")
	QuestsFu:RegisterDefaults("Comments", "profile", {
		lightheaded = true,
		data = {},
		strata = "HIGH",
	})
	QuestsFu.options.args.Comments = {
		name = L["Comments"],
		desc = L["Display quest comments."],
		type = "group",
		args = {
			lightheaded = {
				name = "LightHeaded",
				desc = "LightHeaded",
				type = 'toggle',
				get = function() return self.db.profile.lightheaded end,
				set = function(t) self.db.profile.lightheaded = t end,
				disabled = function() return not LightHeaded end
			},
			strata = {
				name=AceLibrary("AceLocale-2.2"):new("QuestsFu")["Strata"], type="text", desc=AceLibrary("AceLocale-2.2"):new("QuestsFu")["Adjust the strata of this panel (takes effect after you reload your UI)"],
				get=function() return self.db.profile.strata end,
				set=function(t) self.db.profile.strata = t end,
				validate={'BACKGROUND', 'LOW', 'MEDIUM', 'HIGH', },
				order = 1,
			},
			--This one will look a little weird on the tablet right-click menu, as it'll be duplicating native functionality.  But it's totally worth it to stop people complaining.
			lock = {
				type = 'toggle', name = AceLibrary("AceLocale-2.2"):new("QuestsFu")["Lock"],
				desc = AceLibrary("AceLocale-2.2"):new("QuestsFu")["Lock or unlock this panel"],
				disabled = function() return not tablet:IsRegistered("QuestsFu_Tracker") end,
				get = function() return tablet:IsRegistered("QuestsFu_Tracker") and tablet:IsLocked("QuestsFu_Tracker") end,
				set = function() tablet:ToggleLocked("QuestsFu_Tracker") end,
				order = 1,
			},
			toggle = {
				name = AceLibrary("AceLocale-2.2"):new("QuestsFu")["Enabled"],
				desc = AceLibrary("AceLocale-2.2"):new("QuestsFu")["Suspend/resume this module."],
				type = 'toggle',
				order = -1,
				get = function() return QuestsFu:IsModuleActive(self) end,
				set = function()
					if tablet:IsRegistered('QuestsFu_Comments') then tablet:Close('QuestsFu_Comments') end
					QuestsFu:ToggleModuleActive(self)
				end
			},
		},
	}
end

function QuestsFu_Comments:OnEnable()
	self:SecureHook(QuestsFu, "ShowLog")
end

function QuestsFu_Comments:ShowLog(object, questid)
	--self.questid = questid
	if questid and LightHeaded and self.db.profile.lightheaded and QuestsFu:IsModuleActive('Details') then
		-- (If the details module isn't active, this is all unnecessary.)
		-- I thought this would work, but it locks up the game:
		--local startingQuestLogSelection = GetQuestLogSelection()
		--SelectQuestLogEntry(questid)
		--LightHeaded.QuestOnClick()
		--SelectQuestLogEntry(startingQuestLogSelection)
		
		-- Instead, for now:
		self:ScheduleEvent(self.Update, 0, self) --Schedule an event because tablet bugs out otherwise.
	end
end

function QuestsFu_Comments:Update()
	if not tablet:IsRegistered('QuestsFu_Comments') then
		local huffman = DongleStub("Huffman-1.0")
		
		local quests, rev
		if UnitFactionGroup("player") == "Alliance" then
			quests = LH_Alliance
			rev = LH_Alliance_Rev
		else
			quests = LH_Horde
			rev = LH_Horde_Rev
		end
		
		local function close()
			self.questid = nil
		end
		
		local detail = QuestsFu:GetModule('Details')
		
		tablet:Register('QuestsFu_Comments', 'detachedData', self.db.profile.data, 'cantAttach', true, 'dontHook', true,
			'hideWhenEmpty', true, 'showTitleWhenDetached', true, 'strata', self.db.profile.strata, 'minWidth', 300,
			'menu', function() dewdrop:FeedAceOptionsTable(QuestsFu.options.args.Comments) end,
			'children', function()
				-- Much of this was taken from LightHeaded itself.
				if detail.questid then
					local title, level, tag = quixote:GetQuestById(detail.questid)
					local color = GetDifficultyColor(level)
					tablet:SetTitle("Comments for "..QuestsFu:MakeTag(level, tag)..title)
					tablet:SetTitleColor((color and color.r) or 1, (color and color.g) or 1, (color and color.b) or 1)
					
					local cat = tablet:AddCategory('text', 'LightHeaded', 'columns', 1, 'wrap', true, 'child_func', LightHeaded.OnHyperlinkClick, 'child_arg1', LightHeaded, 'justify', 'CENTER')
					
					local key = string.format("%s:%s", title, level)
					local entry = quests[key]
					if not entry then
						cat:AddLine('text', "No comments found...", 'func', false)
						return
					end
					
					local qid,sname,ename,category = entry[1]:match("^(%d+):(.+):(.+):(.+)$")
					for i=2,#entry do
						local v = huffman.decode(entry[i], rev)
						local cid,rating,indent,parent,date,poster,comment = v:match("^%d+:(%d+):(%-?%d+):(%d+):(%d+):(%d+/%d+/%d+ %d+:%d+:%d+):([^:]+):(.+)$")
						
						local link = ("comment:%s:%d:%d"):format(title, level, i)
						comment = comment:gsub("<br>", "\n")
						
						cat:AddLine('text', ("|cFF66FF66[%s - %s]|r"):format(poster, date), 'arg2', link, 'wrap', true)
						cat:AddLine('text', comment, 'arg2', link, 'wrap', true)
						cat:AddLine('func', false)
					end
				end
			end)
		tablet:Open('QuestsFu_Comments')
	end
	tablet:Refresh('QuestsFu_Comments')
end
