// Copyright © Selmo Technology GmbH. All Rights Reserved

using Novus.Connectivity.Service;
using SelmoStudio.Hmi.Server.ProcessValue.Services;

namespace SelmoStudio.Hmi.Server.ProcessValue
{
    public class ProcessValuesHandler : IProcessValuesHandler, IDisposable
    {
        private Func<Task>? _onIntervalElapsedCallback;

        public virtual void Register(ValuesConnectionRegistration registration, IProcessValuePollingService registrationService)
        {
          
        }

        public virtual void Unregister(ValuesConnectionRegistration registration, IProcessValuePollingService registrationService)
        {
            if (registration != null)
            {
                registrationService.UnRegisterValues(registration.Id);
            }
        }

        public virtual void UnregisterOnIntervalElapsed(IProcessValuePollingService registrationService)
        {
            registrationService.OnIntervalElapsed -= IntervalElapsed;
        }

        public virtual void RegisterOnIntervalElapsed(IProcessValuePollingService registrationService)
        {
            registrationService.OnIntervalElapsed += IntervalElapsed;
        }

        public void SetIntervalElapsedCallback(Func<Task> callback)
        {
            _onIntervalElapsedCallback = callback;
        }

        private void IntervalElapsed(object? sender, EventArgs e)
        {
            Task.Run(async () =>
            {
                if (_onIntervalElapsedCallback != null)
                {
                    try
                    {
                        await _onIntervalElapsedCallback.Invoke();
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex);
                    }
                }
            });
        }

        public void Dispose()
        {
            _onIntervalElapsedCallback = null;
        }
    }
}