local AceOO = AceLibrary("AceOO-2.0")
local BZ = AceLibrary("Babble-Zone-2.2")
local RollCall = AceLibrary("RollCall-1.0")
local Tourist = AceLibrary("Tourist-2.0")

GuildPoint = AceOO.Class(Waypoint)

GuildPoint.Watcher = {}

GuildPoint.prototype.Pending = "Pending update"

-- Store the guildmember in the static class for later 
-- reference. WaypointID is the guildmember name.
function GuildPoint.prototype:init(memberName)
	AceLibrary.argCheck(self, memberName, 2, "string")
	
	for name in RollCall:GetIterator("NAME") do
		if string.find(string.lower(name), string.lower(memberName)) then
			GuildPoint.super.prototype.init(self, name)
			if not GuildPoint.Watcher[name] then
				GuildPoint.Watcher[name] = self
			end	
			break
		end
	end
--	GuildPoint.super.prototype.init(self, -1)
end

-- Is this the same note as the waypoint?
function GuildPoint.prototype:MatchNote(memberName)
	return self.WaypointID == memberName
end
	
function GuildPoint.prototype:UpdateLocation(zone, _x, _y)
	local ezone = RollCall:GetEnglishZone(self.WaypointID)
	local x,y = Tourist:TransposeZoneCoordinate(_x, _y, ezone, RollCall:GetZone(self.WaypointID))
	self.Zone, self.x, self.y = zone, x, y
end

function GuildPoint.prototype:GetDistance()
	return GuildPoint.super.prototype.GetDistance(self)
end

-- Use the Guildmember name as the Title
function GuildPoint.prototype:ToString()
	if self:IsReady() then
		return self.WaypointID
	else
		return self.Pending
	end
end

function GuildPoint.prototype:IsReady()
	if self.Zone ~= "Limbo" and self.x ~= -1 and self.y ~= -1 then 
		return true 
	else
		if not self.firstCheck then 
			self.firstCheck = time()
		else
			local delay = time() - self.firstCheck - (RollCall:GetNumOnline()/5)
			if delay < 5 then
				self.Pending = "Waiting for Location update"
			elseif delay < 9 then
				self.Pending = "Guild Member not locatable"
			else -- if they haven't updated in the normal update period
				self:Cancel()
			end
		end
		return false
	end
end

function GuildPoint.prototype:Cancel()
	GuildPoint.Watcher[self.WaypointID] = nil
	self.Icon, self.Db, self.Data = nil
	GuildPoint.super.prototype.Cancel(self)
end

-- Are we online?
function GuildPoint.prototype:IsValid()
	return (self.WaypointID ~= -1) and RollCall:IsMemberOnline(self.WaypointID)
end
