// Copyright © Selmo Technology GmbH. All Rights Reserved

using Microsoft.AspNetCore.Components;
using SelmoStudio.Hmi.Server.SelmoHmi.Dialog.Model;

namespace SelmoStudio.Hmi.Server.SelmoHmi.Dialog.Service
{
    public class HmiDialogService : IHmiDialogService, IDisposable
    {
        private readonly IDialogService _dialogService;
        private IDialog? _dialog;

        public string Id { get; }

        public HmiDialogService(IDialogService dialogService, string id)
        {
            _dialogService = dialogService;
            Id = id;
            _dialogService.OnClose += OnDialogClose;
        }

        public async Task OpenDialogAsync<T>(string title, string width, string height, Dictionary<string, object> parameters) where T : ComponentBase
        {
            if (_dialog == null)
            {
                _dialog = new Model.Dialog
                {
                    Title = title,
                    Type = typeof(T),
                    Parameters = parameters,
                    Options = new DialogOptions
                    {
                        Width = width,
                        Height = height,
                        Resizable = false,
                        Draggable = false,
                        AutoFocusFirstElement = false
                    }
                };

                await _dialogService.OpenAsync<T>(_dialog.Title, _dialog.Parameters, _dialog.Options);
            }
        }

        public void CloseDialog()
        {
            _dialogService.Close();
        }

        private void OnDialogClose()
        {
            _dialog = null;
        }

        public void Dispose()
        {
            _dialogService.OnClose -= OnDialogClose;
            (_dialogService as IDisposable)?.Dispose();
        }
    }
}