// Copyright © Selmo Technology GmbH. All Rights Reserved

using SelmoStudio.Hmi.Plugin.Model.WellKnown;
using SelmoStudio.Hmi.Server.Alarms.Service;
using SelmoStudio.Hmi.Server.ProcessValue.Services;
using SelmoStudio.Hmi.Server.SelmoHmi.Connection.Component;
using SelmoStudio.Hmi.Server.SelmoHmi.Dialog.Service;
using SelmoStudio.Hmi.Server.Shared.Resources;

namespace SelmoStudio.Hmi.Server.SelmoHmi.Connection.Service
{
    public class ConnectionService : IConnectionService, IDisposable
    {
        private const string DialogStyleWidth = "40%";
        private const string DialogStyleHeight = "20vh";

        private readonly IHmiDialogService _hmiDialogService;
        private readonly IProcessValuePollingService _processValuePollingService;

        public ConnectionService(IDialogService dialogService, IProcessValuePollingService processValuePollingService)
        {
            _processValuePollingService = processValuePollingService;
            _hmiDialogService = new HmiDialogService(dialogService, WellKnownElementIds.ReconnectionService_ReconnectDialogId);
        }

        public Action OnConnectionEstablished { get; set ; }

        public void Connect()
        {
            _processValuePollingService.Reconnect();

            var isConnected = _processValuePollingService.IsConnectionActive();

            if (isConnected)
            {
                OnConnectionEstablished?.Invoke();
            }

            ShowConnectionStatus(isConnected);
        }

        private void ShowConnectionStatus(bool isConnected)
        {
            var resultMessage = isConnected ? $"{HmiResource.ServerConnection}: {HmiResource.Connected}"
                    : $"{HmiResource.ServerConnection}: {HmiResource.Disconnected}";
            var parameters = new Dictionary<string, object>() { { "Message", resultMessage }, { "HmiDialogService", _hmiDialogService } };

            _hmiDialogService.OpenDialogAsync<ConnectionStatusComponent>(HmiResource.ServerConnection, DialogStyleWidth, DialogStyleHeight, parameters);
        }

        public void Dispose()
        {
            if (_hmiDialogService != null)
            {
                ((HmiDialogService)_hmiDialogService).Dispose();
            }
        }
    }
}
