using adas_core.Application.Services.Interfaces;
using adas_core.Application.Subscriptions;
using MongoDB.Bson;
namespace adas_core.Application.Services;
///
/// Provides operations for managing subscribers by implementing the contract.
/// Acts as the concrete service layer responsible for subscriber-related functionality.
///
public class SubscribersService : ISubscribersService
{
private readonly List _subscribers = [];
///
/// Retrieves a thread-safe snapshot of the current list of WebSocket subscribers.
///
/// A new containing a copy of the current subscribers.
public List GetSubscribers()
{
lock (_subscribers)
{
return _subscribers.ToList();
}
}
///
/// Retrieves a WebSocket subscriber by its connection identifier, returning null if no matching subscriber is found.
/// Thread-safe access to the subscribers collection is ensured via locking.
///
/// The unique connection identifier of the subscriber to look up.
/// The matching if found; otherwise, null.
public WsSubscriber? GetById(string contextConnectionId)
{
lock (_subscribers)
{
return _subscribers.FirstOrDefault(s => s.Id == contextConnectionId);
}
}
///
/// Retrieves all subscribers whose associated location identifiers include the specified point-of-contact identifier.
/// Ensures thread-safe access to the underlying subscriber collection during the read operation.
///
/// The point-of-contact identifier used to match subscribers by their location list.
/// A list of instances that have in their location identifiers; returns an empty list when no matches are found.
public List GetByPocId(ObjectId pocId)
{
lock (_subscribers)
{
return _subscribers.Where(s => s.LocationIds.Contains(pocId)).ToList();
}
}
///
/// Removes all subscriber connections matching the specified connection identifier in a thread-safe manner.
///
/// The unique identifier of the connection to remove.
/// The number of connections that were removed from the subscribers list.
public int RemoveConnectionById(string contextConnectionId)
{
lock (_subscribers)
{
return _subscribers.RemoveAll(s => s.Id == contextConnectionId);
}
}
///
/// Adds a WebSocket subscriber to the internal subscribers collection in a thread-safe manner.
/// Ensures that concurrent calls to add subscribers are serialized to prevent race conditions.
///
/// The WebSocket subscriber to add to the collection.
public void AddSubscriber(WsSubscriber subscriber)
{
lock (_subscribers)
{
_subscribers.Add(subscriber);
}
}
}