namespace Universal.IO;

public class Data(byte[] rawData, Connection? connection = null, DateTime? dateTime = default)
{
    public byte[] RawData { get; } = rawData;
    public Connection? Connection { get; } = connection;
    public DateTime DateTime { get; internal set; } = dateTime is null ? DateTime.Now : dateTime.Value;
}

public interface ISender
{
    ISender? NextSender { get; set; }
    bool Send(Data data);
}

public interface IReceiver
{
    IReceiver? PrevReceiver { get; set; }
    bool Receive(Data data);
}

public interface IConnect
{
    IConnect? PrevConnector { get; set; }
    void Connected(Connection connection);
    void Disconnected(Connection connection);
}

//public interface ITcpConnectNority
//{
//    void Connect(string ip, int port);
//    void DisConnect(string ip, int port);
//}


public interface IFilter : ISender, IReceiver, IConnect
{
    public static IFilter operator >>(IFilter filter1, IFilter filter2)
    {
        filter1.NextSender = filter2;
        filter2.PrevReceiver = filter1;
        filter2.PrevConnector = filter1;

        return filter2;
    }

    bool IReceiver.Receive(Data data)
    {
        return this.PrevReceiver?.Receive(data) == true;
    }

    bool ISender.Send(Data data)
    {
        return this.NextSender?.Send(data) == true;
    }

    void IConnect.Connected(Connection connection)
    {
        this.PrevConnector?.Connected(connection);
    }

    void IConnect.Disconnected(Connection connection)
    {
        this.PrevConnector?.Disconnected(connection);
    }
}

public abstract class BaseFilter : IFilter
{
    public static BaseFilter operator >>(BaseFilter filter1, BaseFilter filter2)
    {
        filter1.NextSender = filter2;
        filter2.PrevReceiver = filter1;
        filter2.PrevConnector = filter1;

        return filter2;
    }

    public ISender? NextSender { get; set; }
    public IReceiver? PrevReceiver { get; set; }
    public IConnect? PrevConnector { get; set; }

    public virtual bool Receive(Data data)
    {
        return this.PrevReceiver?.Receive(data) == true;
    }

    public virtual bool Send(Data data)
    {
        return this.NextSender?.Send(data) == true;
    }

    public virtual void Connected(Connection connection)
    {
        this.PrevConnector?.Connected(connection);
    }

    public virtual void Disconnected(Connection connection)
    {
        this.PrevConnector?.Disconnected(connection);
    }
}