// Copyright © Selmo Technology GmbH. All Rights Reserved

using Microsoft.AspNetCore.Components;
using Novus.Connectivity.Service;
using SelmoStudio.Hmi.Server.ProcessValue;
using SelmoStudio.Hmi.Server.ProcessValue.Services;

namespace SelmoStudio.Hmi.Server.SelmoHmi.BaseComponent
{
    public abstract class BaseComponentWithProcessValueHandler : ComponentBase
    {
        private bool _disposed;
        private IProcessValuesHandler _processValueHandler;

        [Inject]
        private ILogger<BaseComponentWithProcessValueHandler> _logger { get; set; }

        [Inject]
        protected IProcessValuePollingService RegistrationService { get; set; }

        protected ValuesConnectionRegistration Registration;

        protected abstract void CreateRegistration();

        protected abstract Task OnIntervalElapsedAsync();

        protected override async Task OnInitializedAsync()
        {
            _processValueHandler = new ProcessValuesHandler();

            if (Registration != null)
            {
                _processValueHandler.Unregister(Registration, RegistrationService);
            }

            CreateRegistration();

            if (Registration != null)
            {
                RegisterToService();
            }

            await base.OnInitializedAsync();
        }

        protected void UpdateRegistration()
        {
            if (_processValueHandler != null)
            {
                if (Registration != null)
                {
                    UnregisterService();
                }

                CreateRegistration();
                RegisterToService();
            }
        }

        private void RegisterToService()
        {
            _processValueHandler.SetIntervalElapsedCallback(() => OnIntervalElapsedAsync());
            _processValueHandler.RegisterOnIntervalElapsed(RegistrationService);
            _processValueHandler.Register(Registration, RegistrationService);
        }

        private void UnregisterService()
        {
            if (Registration != null)
            {
                _processValueHandler.UnregisterOnIntervalElapsed(RegistrationService);
                _processValueHandler.Unregister(Registration, RegistrationService);
            }
        }

        protected async ValueTask HandleUnregistration()
        {
            UnregisterService();
            _processValueHandler?.Dispose();

            await Task.CompletedTask;
        }

        protected async ValueTask BaseDisposeAsync()
        {
            if (!_disposed)
            {
                await HandleUnregistration();
                _disposed = true;
            }
        }
    }
}