local addonName, addon = ...

BINDING_NAME_GTIPNOTES_PRINT = "Print ToolTip Note"

StaticPopupDialogs["GTipNotes"] = {
	button1 = "Set",
	button2 = "Cancel",
	hasEditBox = true,
	hideOnEscape = true,
	text = "Set a note for |cffff4488%s|r.",
	timeout = 0,
	whileDead = true,
	EditBoxOnEnterPressed = function(self, data)
		local note = self:GetText():trim()
		if note == "" then
			note = nil
		end
		GTipNotesDB[data] = note
		self:GetParent():Hide()
	end,
	EditBoxOnEscapePressed = function(self)
		self:GetParent():Hide()
	end,
	OnAccept = function(self, data)
		local note = _G[self:GetName() .. 'EditBox']:GetText():trim()
		if note == "" then
			note = nil
		end
		GTipNotesDB[data] = note
	end
}

function addon:GTipNotesRun(note)
	local name = UnitName('target')
	local note = GTipNotesDB[name]
	if note == "" then
		note = GTipNotesDB[name]
	end
	StaticPopup_Show("GTipNotes", name, nil, name)
	if note then
		name = StaticPopup_Visible("GTipNotes")
		if name then
			_G[name .. 'EditBox']:SetText(note)
		end
	end
end 
function addon:GTipNotesPrint(note)
	local name = UnitName("target")
	local note = GTipNotesDB[name]
	if not note then return end
	if GetNumRaidMembers() > 0 then
		SendChatMessage(name .. ": " .. note, "RAID")
	elseif GetNumPartyMembers() > 0 then
		SendChatMessage(name .. ": " .. note, "PARTY")
	else
		SendChatMessage(name .. ": " .. note, "SAY")
	end
end

SlashCmdList["GTIPNOTES_SHORTHAND"] = function(note)
	if UnitExists('target') then
		local name = UnitName('target')
		note = note:trim()
		if note == "" then
			note = GTipNotesDB[name]
		end
		StaticPopup_Show("GTipNotes", name, nil, name)
		if note then
			name = StaticPopup_Visible("GTipNotes")
			if name then
				_G[name .. 'EditBox']:SetText(note)
			end
		end
	else
		print("You must target something to add a note.")
	end
end
SLASH_GTIPNOTES_SHORTHAND1 = "/gtipnotes"
SLASH_GTIPNOTES_SHORTHAND2 = "/gtipnote"
SLASH_GTIPNOTES_SHORTHAND3 = "/tipnote"
SLASH_GTIPNOTES_SHORTHAND3 = "/gtn"

addon.RegisterEvent("TooltipNotes-Initialize", 'PLAYER_LOGIN', function(self, event)
	addon.UnregisterEvent(self, event)
	if type(GTipNotesDB) ~= 'table' then
		GTipNotesDB = { }
	end
	GameTooltip:HookScript('OnTooltipSetUnit', function(self)
		local note = GTipNotesDB[self:GetUnit()]
		if note then
			self:AddLine("|cffff4488Note:|r " .. note, 0.5, 0.5, 0.5, 1)
		end
	end)
end)