
SpawnPoint = Entity:createSubClass();
registerSpawn("SpawnPoint");

spawnPointList = {};

function SpawnPoint:init()

   self:setEditorVisibleOnly(true);
   self:registerMe();

   self.usedThisFrame = false;

   self:setLayer(3);

end

function SpawnPoint:save()

   return {};

end

function SpawnPoint:registerMe()

   spawnPointList[self] = true;

end

function SpawnPoint:initFromSave(saveData)

   self.usedThisFrame = false;

   self:registerMe();

end

function SpawnPoint:destruct()

   spawnPointList[self] = nil;

end

function SpawnPoint:hasLoiteringPlayers()

   local boxRadius = 128;
   local x, y = self:getPos();

   local nearbyEnts = getEntsTouchingBox(
      self:getLayer(),
      x - boxRadius,
      y + boxRadius,
      x + boxRadius,
      y - boxRadius);

   for k, v in pairs(nearbyEnts) do

      local ent = entitiesByName[v];

      if ent and ent.isActor then
         return true;
      end

   end

   return false;

end

function SpawnPoint:postUpdate()

   self.usedThisFrame = false;

end

function getRandomSpawnPoint()

   local numPoints = 0;
   local convertedList = {};

   for k,v in pairs(spawnPointList) do
      numPoints = numPoints + 1;
      convertedList[numPoints] = k;
   end

   if numPoints >= 1 then

      local numTries = 10;
      
      while numTries > 0 do
         
         local pointIndex = math.random(1, numPoints);

         if not (convertedList[pointIndex]:hasLoiteringPlayers()) then
            if not convertedList[pointIndex].usedThisFrame then
               convertedList[pointIndex].usedThisFrame = true;
               return convertedList[pointIndex];
            end
         end

         numTries = numTries - 1;

      end

   end

   return nil;

end


