local Communication = AsheylaLib:NewModule("VersionCommunication");
local find = string.find;
local match = string.match;

local f = CreateFrame("Frame");
f:RegisterEvent("CHAT_MSG_ADDON");
f:RegisterEvent("PLAYER_ENTERING_WORLD");
f:RegisterEvent("PARTY_MEMBERS_CHANGED");
f:RegisterEvent("RAID_ROSTER_UPDATE");

f:SetScript("OnEvent", function(self, event, ...)
    Communication[event](Communication, ...);
end);

function Communication:CHAT_MSG_ADDON(pre, msg, loc, sender)
    if pre == "DTMR" then
        local version = AsheylaLib:ReturnVersion();
        if msg == "request" then
            SendAddonMessage("DTMR", "version:"..version, loc);
        elseif find(msg, "^version") then
            version = self:Get("version") or version;
            local compver = match(msg,"version%:(.+)")
            if (compver) and not find(compver, "[^%d%.]") and (compver > version) then
                self:FlagAlert(compver);
            end
        end
    end
end

function Communication:PLAYER_ENTERING_WORLD()
    if IsInGuild() then self:Ask("GUILD"); end
    self:PARTY_MEMBERS_CHANGED();
    self:RAID_ROSTER_UPDATE();
    self:AlertUser(self:HasFlag());
    f:UnregisterEvent("PLAYER_ENTERING_WORLD");
end

function Communication:PARTY_MEMBERS_CHANGED()
    if GetNumPartyMembers() > 0 then self:Ask("PARTY"); end
end

function Communication:RAID_ROSTER_UPDATE()
    if GetNumRaidMembers() > 0 then self:Ask("RAID"); end
end

function Communication:Ask(loc)
	SendAddonMessage("DTMR", "request", loc);
end

function Communication:AlertUser(flag)
	if flag then AsheylaLib:AlertUser(string.format("There is a new version of DoTimer available: |cff00ff00%s|r.  Please upgrade!", flag)); end
end

function Communication:FlagAlert(ver)
	self:Set("flag", ver);
    self:Set("version", ver);
end

function Communication:HasFlag()
	local flag = self:Get("flag");
	self:Set("flag", nil);
	return flag;
end
