local MSG_PREFIX = "WN-VC"
local INSTALL_VERSION =  GetAddOnMetadata("WhatsNext", "Version");

local function processAddonMessage(prefix,msg,channel,sender) 
	if prefix == MSG_PREFIX then
		local version =  strsplit(",",msg);
		--print(sender, version)
		if version and tonumber(version) and tonumber(version) > tonumber(INSTALL_VERSION) then
			INSTALL_VERSION = version
			print("A newer version (|cFF69CCF0".. INSTALL_VERSION .. "|r) of |cFFFFFF00'Whats Next?'|r has been detected!")
		elseif version and tonumber(version) and tonumber(version) < tonumber(INSTALL_VERSION)  then
			SendAddonMessage(MSG_PREFIX, INSTALL_VERSION, "WHISPER", sender)
		end
	end
end

local function EventFunc(self, event, ...)
	if event == "PLAYER_LOGIN" then
		RegisterAddonMessagePrefix(MSG_PREFIX)
		if GetGuildInfo("player")  then
			SendAddonMessage(MSG_PREFIX, INSTALL_VERSION, "GUILD")
		end
	elseif event == "PLAYER_ENTERING_WORLD" then
		if GetGuildInfo("player")  then
			SendAddonMessage(MSG_PREFIX, INSTALL_VERSION, "GUILD")
		end
	elseif event == "GROUP_JOINED" then
		if IsInGroup(LE_PARTY_CATEGORY_INSTANCE) then
			SendAddonMessage(MSG_PREFIX, INSTALL_VERSION, "INSTANCE_CHAT")
		elseif UnitInRaid("player") then
			SendAddonMessage(MSG_PREFIX, INSTALL_VERSION, "RAID")
		elseif IsInGroup() then
			SendAddonMessage(MSG_PREFIX, INSTALL_VERSION, "PARTY")
		end
	elseif event == "CHAT_MSG_ADDON" then
		processAddonMessage(...)
	end
end

local eventHandler = CreateFrame("Frame", nil, WorldFrame)
eventHandler:SetScript("OnEvent", EventFunc)
eventHandler:RegisterEvent("PLAYER_LOGIN")
eventHandler:RegisterEvent("CHAT_MSG_ADDON")
eventHandler:RegisterEvent("PLAYER_ENTERING_WORLD")
eventHandler:RegisterEvent("GROUP_JOINED")