using BOB.Converters;
using Common.PubEvent;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace BOB.Services
{
    public abstract class PollingRead
    {
        private CancellationTokenSource _pollingCancellationTokenSource;
        private Task? _pollingTask;
        public int PollingInterval = 1000; 
        public string DeviceName{get;set;}="";
         private bool IsConnect{ get; set; }=false;
        public PollingRead(IContainerProvider containerProvider)
        {
            var _eventAggregator = containerProvider.Resolve<IEventAggregator>();
            _eventAggregator.GetEvent<ConnectionChangeEvent>().Subscribe(PollingConnection);
        }

        private void PollingConnection((string, bool) tuple)
        {
            var (device, isConnect) = tuple;
            //System.Diagnostics.Debug.WriteLine($"PollingRead收到连接状态变化事件:设备={device},状态={isConnect}");
            if (device== DeviceName)
            {
                IsConnect = isConnect;
            }
        }

        public void StartPolling()
        {
            if (_pollingTask != null)
                return;

            if (_pollingCancellationTokenSource == null || _pollingCancellationTokenSource.IsCancellationRequested)
                _pollingCancellationTokenSource = new CancellationTokenSource();

            _pollingTask = Task.Run(() => PollingLoop(_pollingCancellationTokenSource.Token));
        }

        public void StopPolling()
        {
            _pollingCancellationTokenSource?.Cancel();
            _pollingTask = null;
        }

        private async Task PollingLoop(CancellationToken ct)
        {
            while (!ct.IsCancellationRequested)
            {
                if (IsConnect)
                {
                    await Task.Delay(PollingInterval, ct);

                    try
                    {
                        await ReadDeviceDataAsync(ct);
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine($"轮询过程中发生错误: {ex.Message}");
                    }
                }
            }
        }
        public abstract Task ReadDeviceDataAsync(CancellationToken ct = default);
      
        
    }
}
