using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Mail;
using System.Text;
using System.Threading.Tasks;
namespace Firebird2D.EventPipelines
{
///
/// Eventpypeline which transports an event to every Subscyber
///
/// Event Arguments for the Pipeline event
public class Pipeline : I_Pipeline where T : EventArgs
{
///
/// Class witch owns the Pipeline and has the right to send events or delete the pipeline
///
public object PipelineMaster { get; }
//EventHandler to which the subscribers subribe.
private event EventHandler? OnEvent;
///
/// Pipeline Constructor
///
/// Every pipeline needs a Master which is able to send events or Destroy the pipeline
public Pipeline(object pipelineMaster)
{
PipelineMaster = pipelineMaster;
}
///
/// Check if no one subscribed to the event
///
public bool IsEventEmpty { get { return OnEvent != null; } }
///
/// Subscribe to this event Pipeline
///
/// Handler witch should be Invoked when the event is send
public void Subscribe(Delegate handler)
{
OnEvent += (EventHandler)handler;
}
///
/// Unsubscribe from this event Pipeline
///
/// Handler witch should be removed from the Pipeline
public void Unsubscribe(Delegate handler)
{
OnEvent -= (EventHandler)handler;
}
///
/// Method to send an event through the pipeline
///
/// Sneder object must be Pipelinemaster or the Pipeline throws an exception
/// Arguments that should be sent
/// Exception when sender or arguments ar null
/// Exception wehn Arguments are not equal the Pipeline type
/// Exception when sender is not Pipeline master
public void SendEvent(object sender, T args)
{
if (sender == null || args == null) throw new ArgumentNullException(nameof(sender));
if (args is not T) throw new ArgumentException($"Invalid EventArgs type. Expected {typeof(T)}");
if (sender.Equals(PipelineMaster)) throw new InvalidDataException("Only the pipeline master is allowed to send events through this pipeline.");
OnEvent?.Invoke(sender, args);
}
}
}