

local RangesCache = {}
local Ranges = {}
local RangeWatcher = CreateFrame("Frame")
local nextRangeCheckup = 0
local currentTime = 0
local updateFreq = .75

local function CheckRanges(self)
	currentTime = GetTime()
	if currentTime < nextRangeCheckup then return end
	nextRangeCheckup = currentTime + updateFreq
	local group, size, index, unitid, inRange
	local estRange = nil
	-- Check Group Type
	if UnitInRaid("player") then group = "raid"; size = GetNumRaidMembers() - 1
	elseif UnitInParty("player") then group = "party"; size = GetNumPartyMembers()
	else group = nil end

	-- Cycle through Group
	if group then
		for index = 1, size do
			unitid = group..index
			
			inRange = UnitInRange(unitid)
			if inRange then
				estRange = 40
				if CheckInteractDistance(unitid, 4) then estRange = 28
					if CheckInteractDistance(unitid, 2) then estRange = 11.11
						if CheckInteractDistance(unitid, 3) then estRange = 9.9
				end end end
			end
			
			Ranges[UnitName(unitid)] = estRange
		end
	end
	
	-- Update the nameplates
	
end

local function TestTargetRange(self)
	currentTime = GetTime()
	if currentTime < nextRangeCheckup then return end
	nextRangeCheckup = currentTime + updateFreq
	local group, size, index, unitid, inRange, unitname
	local estRange = nil
	-- Check Group Type
	unitid = "target"
	unitname = UnitName(unitid)
	
	if unitname then
		--if UnitInRange(unitid) then
			--estRange = 40
			if CheckInteractDistance(unitid, 4) then estRange = 28
				if CheckInteractDistance(unitid, 2) then estRange = 11.11
					if CheckInteractDistance(unitid, 3) then estRange = 9.9
			end end end
		--end
				
		print(GetTime(), unitname, estRange)
		Ranges[unitname] = estRange
	end
	
	-- Update the nameplates
	TidyPlates:Update()
end

local function DoEvents(self, event, ...) end
--RangeWatcher:SetScript("OnEvent", DoEvents )
--RangeWatcher:SetScript("OnUpdate", TestTargetRange)


---------------------------------------------------------------------------

---------------
-- Class Widget
---------------
local classWidgetPath = "Interface\\Addons\\TidyPlates\\Widgets\\ClassWidget\\"

local function UpdateRangeWidget(self, unit)
		if unit.isTarget then 
			self.Range:SetText(Ranges[unit.name])
			self:Show()
		else self:Hide() end
end

local function CreateRangeWidget(parent)
	local frame = CreateFrame("Frame", nil, parent)
	frame:SetWidth(16); frame:SetHeight(16)
	--  [[ Time Text
	frame.Range = frame:CreateFontString(nil, "OVERLAY")
	frame.Range:SetFont("Interface\\Addons\\TidyPlates\\Media\\LiberationSans-Regular.ttf",9, "OUTLINE")
	frame.Range:SetShadowOffset(1, -1)
	frame.Range:SetShadowColor(0,0,0,1)
	frame.Range:SetPoint("CENTER")
	frame.Range:SetWidth(26)
	frame.Range:SetHeight(16)
	frame.Range:SetJustifyH("RIGHT")
	frame:Hide()
	frame.Update = UpdateRangeWidget
	return frame
end

TidyPlatesWidgets.CreateRangeWidget = CreateRangeWidget