using InABox.Core;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
namespace InABox.Core
{
public interface IPollHandler
{
Type Type { get; }
///
/// Polls for notifications, called on client connection.
///
/// New notifications
IEnumerable Poll(Guid session);
}
public class PollHandler : IPollHandler
{
public delegate IEnumerable PollEvent(Guid session);
public event PollEvent? OnPoll;
public Type Type => typeof(TNotification);
public PollHandler() { }
public PollHandler(PollEvent poll)
{
OnPoll += poll;
}
public IEnumerable Poll(Guid session) => (OnPoll?.Invoke(session) ?? Array.Empty()).Cast();
}
public abstract class Notifier
{
private List Handlers = new List();
protected abstract void NotifyAll(TNotification notification);
protected abstract void NotifySession(Guid session, TNotification notification);
protected abstract void NotifySession(Guid session, Type TNotification, object? notification);
protected abstract IEnumerable GetUserSessions(Guid user);
protected abstract IEnumerable GetSessions(Platform platform);
public void Push(TNotification notification)
{
NotifyAll(notification);
}
public void Push(Guid session, TNotification notification)
{
NotifySession(session, notification);
}
public void PushUser(Guid user, TNotification notification)
{
foreach (var session in GetUserSessions(user))
{
NotifySession(session, notification);
}
}
public void Push(Platform platform, TNotification notification)
{
foreach (var session in GetSessions(platform))
{
NotifySession(session, notification);
}
}
public void Poll(Guid session)
{
foreach (var handler in Handlers)
{
foreach (var notification in handler.Poll(session))
{
NotifySession(session, handler.Type, notification);
}
}
}
public void AddPollHandler(PollHandler handler)
{
Handlers.Add(handler);
}
public void AddPollHandler(PollHandler.PollEvent poll)
{
Handlers.Add(new PollHandler(poll));
}
}
}