namespace MinicsConsole.Helper;

public class Mini8DataDispatcher(ILog log)
{
    private readonly ConcurrentDictionary<string, IMini8DataNotifier> _Connectors = [];

    public bool TryAddNotifier(string name, IMini8DataNotifier connector)
    {
        return _Connectors.TryAdd(name, connector);
    }

    public bool TryRemoveConnector(string name)
    {
        return _Connectors.TryRemove(name, out _);
    }

    public void ChannelInfoNotify(byte mini8, byte channel, ChannelData channelData)
    {
        if (channelData is null)
            return;
        Parallel.ForEach(_Connectors.Values, item =>
        {
            try
            {
                item?.ChannelInfoNotify(mini8, channel, channelData);
            }
            catch
            {
                log?.Warning($"DataDispatcher try send ChannelInfoNotify failed {item.Name} mini8 {mini8} channel {channel}");
            }
        });
    }

    public void AlarmNotify(byte mini8, byte channel, float temperature)
    {
        Parallel.ForEach(_Connectors.Values, item =>
        {
            try
            {
                item.AlarmNotify(mini8, channel, temperature);
            }
            catch
            {
                log.Warning($"DataDispatcher try send AlarmNotify failed {item.Name} mini8 {mini8} channel {channel}");
            }
        });
    }

    public void AlarmTcBrockenNotify(byte mini8, byte channel)
    {
        Parallel.ForEach(_Connectors.Values, item =>
        {
            try
            {
                item.AlarmTcBrockenNotify(mini8, channel);
            }
            catch
            {
                log.Warning($"DataDispatcher try send AlarmTcBrockenNotify failed {item.Name} mini8 {mini8} channel {channel}");
            }
        });
    }

    public void Mini8Connect(byte mini8Index)
    {
        Parallel.ForEach(_Connectors.Values, item =>
        {
            try
            {
                item.Mini8ConnectNotify(mini8Index, true);
            }
            catch
            {
                log.Warning($"DataDispatcher try send Mini8Connect to failed {item.Name} mini8 {mini8Index}");
            }
        });
    }

    public void Mini8Disconnect(byte mini8Index)
    {
        Parallel.ForEach(_Connectors.Values, item =>
        {
            try
            {
                item.Mini8ConnectNotify(mini8Index, false);
            }
            catch
            {
                log.Warning($"DataDispatcher try send Mini8Disconnect failed {item.Name} mini8 {mini8Index}");
            }
        });
    }
}
