using Microsoft.AspNetCore.Components;
using Microsoft.JSInterop;
using System;
using System.Threading.Tasks;
using WK5.Core.PageModels;

namespace WK5_Blazor.Components.Modals
{
    public class ModalBase : ComponentBase
    {
#nullable disable
        [Inject] private IJSRuntime jsRuntime { get; set; }
#nullable enable

        [Parameter] public bool Show { get; set; }
        [Parameter] public string Title { get; set; } = String.Empty;
        [Parameter] public EventCallback OnClosed { get; set; }

        protected string ModalSizeClass => ModalSize switch
        {
            ModalSize.Default => "modal-dialog",
            ModalSize.SM => "modal-dialog modal-sm",
            ModalSize.LG => "modal-dialog modal-lg",
            ModalSize.XL => "modal-dialog modal-xl",
            ModalSize.XXL => "modal-dialog modal-xxl",
            _ => "modal-dialog"
        };

        [Parameter] public ModalSize ModalSize { get; set; } = ModalSize.Default;
        /// <summary>
        /// Gibt an, ob das Modal innerhalb eines weiteren Modals geöffnet wird. Wenn ja, dann erhält das Modal noch zusätzlich die CSS Klasse
        /// .double-overlay
        /// </summary>
        [Parameter] public bool DoubleOverlay { get; set; } = false;
        [Parameter] public string CloseBtnClass { get; set; } = "btn-danger";


        private string _modalId = Guid.NewGuid().ToString();
        private DotNetObjectReference<ModalBase> _reference;
        private IJSObjectReference? jsModule;

        private bool _setup = false;

        public ModalBase()
        {
            _reference = DotNetObjectReference.Create<ModalBase>(this);
        }

        protected override async Task OnParametersSetAsync()
        {
            jsModule = await jsRuntime.InvokeAsync<IJSObjectReference>("import", "./js/ModalLayers.js");

            if (this.Show && !_setup) { 
                if(jsModule is not null)
                {
                    await jsModule.InvokeVoidAsync("register", _modalId, _reference);
                }
                _setup = true;
            }
            else if(!this.Show && _setup)
            {
                if (jsModule is not null)
                {
                    await jsModule.InvokeVoidAsync("closeLayerid", _modalId);
                }                
            }
        }

        [JSInvokable("layerClosed")]
        public async Task LayerClosed()
        {
            await OnClosed.InvokeAsync();
            _setup = false;
        }
    }
}
