using System;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace Pilz.IO
{
    /// <summary>
    /// stellt den Erben "Server" und "Client" 2 verschiedene
    /// Message-Events zur Verfügung, und ein Event-Raisendes Dispose
    /// </summary>
    public abstract class ManagedPipe : IDisposable
    {
        public delegate void EventHandlerWithOneArgument<T0>(T0 Sender);

        /// <summary>
        /// Zur Ausgabe chat-verwaltungstechnischer Status-Informationen
        /// </summary>
        public event EventHandler<DataEventArgs> StatusMessage;
        /// <summary>Zur Ausgabe von Chat-Messages</summary>
        public event EventHandler<DataEventArgs> RetriveData;
        public event EventHandlerWithOneArgument<ManagedPipe> Disposed;

        private bool _IsDisposed = false;

        protected abstract void Dispose(bool disposing);
        public abstract void Send(byte[] bytes);
        public abstract Task SendAsnyc(byte[] bytes);

        protected void OnStatusMessage(DataEventArgs e)
        {
            StatusMessage?.Invoke(this, e);
        }

        protected void OnRetriveData(DataEventArgs e)
        {
            RetriveData?.Invoke(this, e);
        }

        public void RemoveFrom<T>(ICollection<T> Coll) where T : ManagedPipe
        {
            Coll.Remove((T)this);
        }

        public bool IsDisposed
        {
            get
            {
                return _IsDisposed;
            }
        }

        public void AddTo<T>(ICollection<T> Coll) where T : ManagedPipe
        {
            Coll.Add((T)this);
        }

        public void Dispose()
        {
            if (_IsDisposed)
                return;
            _IsDisposed = true;
            Dispose(true);           // rufe die erzwungenen Überschreibungen von Sub Dispose(Boolean)
            Disposed?.Invoke(this);
            GC.SuppressFinalize(this);
        }
    }
}