--[[
	Remove all art placed by a player.
]]

function PlayerSpots:cleanup(player)
	self:_removeUnusedSpots(player)

	for _, placed in ipairs(self.placedSpots) do
		placed.spot:removeArt()
	end

	self.placedSpots = {}
end

function PlayerSpots:_hasArtOnCanvas(canvas)
	for _, placed in ipairs(self.placedSpots) do
		if placed.canvas == canvas then
			return true
		end
	end

	return false
end

function PlayerSpots:_assignRandomSpot(canvas)
	local isSuccess, spot = canvas:getEmptySpot()
	if not isSuccess then
		warn("Cannot find an empty slot in canvas")
		return false, constants.Errors.SpotNotAvailable
	end

	table.insert(self.placedSpots, {
		canvas = canvas,
		spot = spot,
		createdAt = DateTime.now().UnixTimestamp,
	})

	return true, spot
end

function PlayerSpots:_removeOldestArt()
	self.toRemove = 1
end

function PlayerSpots:_removeOldestArtFromCanvas(canvas)
	local toRemove = nil
	for i, placed in ipairs(self.placedSpots) do
		if placed.canvas == canvas then
			-- A spot previously placed by the user has to be freed immediately
			toRemove = i
			placed.spot:removeArt()
			break
		end
	end

	table.remove(self.placedSpots, toRemove)
end

function PlayerSpots:_removeOldestArtFromOtherCanvas(currentCanvas)
	for i, placed in ipairs(self.placedSpots) do
		if placed.canvas ~= currentCanvas then
			self.toRemove = i
			break
		end
	end
end

function PlayerSpots:_removeUnusedSpots(player)
	self.placedSpots = Cryo.List.filter(self.placedSpots, function(placedSpot)
		return placedSpot.spot:hasArt() and placedSpot.spot.ownerUserId == player.UserId
	end)
end

return PlayerSpots
