using System.Collections;
using PralinenPLC.TCP;

namespace PralinenPLC;

public class NetworkResultInformer : TcpServer, IDisposable
{

    private bool _systemReady = false;
    private bool _dataReady = false;
    private bool _dataOk = false;
    private bool _firstConnection = false;
    private static bool _isStarted = false;
    public NetworkResultInformer() : base("0.0.0.0", 42010)
    {
        Console.WriteLine("------");
        Console.WriteLine("NetworkResultInformer");
        Console.WriteLine("------");
        if (!_isStarted)
        {
            Start();
            _isStarted = true;
        }
        _systemReady = true;
        _dataReady = false;
        _dataOk = false;

    }
    List<TcpSession> _sessions = new List<TcpSession>();
    protected override void OnConnected(TcpSession session)
    {
        Console.WriteLine("Client connected");
        Console.WriteLine("------");

        _sessions.Add(session);
        _firstConnection = true;
        base.OnConnected(session);
        SendStatus();
    }

    protected override void OnDisconnected(TcpSession session)
    {
        Console.WriteLine("Client disconnected");
        Console.WriteLine("------");
        _sessions.Remove(session);
        base.OnDisconnected(session);
    }
    byte ConvertToByte(BitArray bits)
    {
        if (bits.Count != 8)
        {
            throw new ArgumentException("bits");
        }
        byte[] bytes = new byte[1];
        bits.CopyTo(bytes, 0);
        return bytes[0];
    }
    public void SendStatus()
    {
        try
        {
            Console.WriteLine($"Sessions:{_sessions.Count}");
            foreach (TcpSession session in _sessions)
            {

                byte[] data = new byte[10];

                BitArray arr = new BitArray(8);

                arr.Set(0, _systemReady);
                arr.Set(1, _dataReady);
                arr.Set(2, _dataOk);
                arr.Set(7, _firstConnection);

                Console.WriteLine($"Sending status: system:{_systemReady} data:{_dataReady} ok:{_dataOk} init:{_firstConnection}");



                data[0] = ConvertToByte(arr);

                session.Send(data);


            }
        }
        catch (Exception e)
        {
            Console.WriteLine(e);
            throw;
        }
        _firstConnection = false;
    }

    public void Reset()
    {
        _dataReady = true;
        _dataOk = true;
        SendStatus();
    }

    public int Delay { get; } = 0;

    public void SignalBad()
    {
        _dataReady = true;
        _dataOk = false;
        SendStatus();
    }

    public void Dispose()
    {
        _systemReady = false;
        _dataReady = false;
        _dataOk = false;
        SendStatus();

    }
}