// Copyright © Selmo Technology GmbH. All Rights Reserved

using Novus.Connectivity.Common;
using Novus.Connectivity.Service;
using Novus.Shared.Types.Interval;
using SelmoStudio.Hmi.Server.Shared.Model;
using SelmoStudio.Hmi.Server.Shared.Service;

namespace SelmoStudio.Hmi.Server.ProcessValue.Services
{
    public class RegistrationService : IRegistrationService
    {
        public IProcessValuePollingService _processValuePollingService;

        public List<ValuesConnectionRegistration> Registrations { get; set; }

        public event EventHandler<RegistrationEventArgs> OnPollingComplete;

        public RegistrationService(IProcessValuePollingService processValuePollingService)
        {
            Registrations = new();
            _processValuePollingService = processValuePollingService;
        }

        public void Init()
        {
            Registrations = new();
            _processValuePollingService.OnIntervalElapsed += IntervallEllapsed;
        }

        private void IntervallEllapsed(object sender, EventArgs e)
        {
            Task.Run(async () =>
            {
                var values = await _processValuePollingService.GetAllValues();
                RegistrationEventArgs args = new RegistrationEventArgs()
                {
                    ProcessValues = values.Value
                };

                if (OnPollingComplete != null)
                {
                    OnPollingComplete(this, args);
                }
            });
        }

        public void AddRegistration(ValuesConnectionRegistration registration)
        {
            if (!Registrations.Contains(registration))
                Registrations.Add(registration);
        }

        public void RemoveRegistration(ValuesConnectionRegistration registration)
        {
            Registrations.Remove(registration);
        }

        public void WriteValue(IProcessValue value)
        {
            _processValuePollingService.WriteValue(value);
        }
    }
}