using FNZCM.BlazorWasm.UI.Components.Bases;
using Microsoft.JSInterop;
using Newtonsoft.Json;

namespace FNZCM.BlazorWasm.UI.Components.FnzBootstrap.Bases
{
    public class FnzBootstrapComponentBase<T, TOptions> : FnzComponentBase, IAsyncDisposable
        where T : class
        where TOptions : OptionsBase, new()
    {
        protected DotNetObjectReference<FnzBootstrapComponentBase<T, TOptions>> dotNetRef { get; }

        public FnzBootstrapComponentBase() => dotNetRef = DotNetObjectReference.Create(this);

        protected override string Prefix => base.Prefix + ".bootstrap";

        protected TOptions _options = new TOptions();

        protected override async Task OnAfterRenderAsync(bool firstRender)
        {
            if (firstRender)
            {
                await JSRuntime.InvokeVoidAsync($"{Prefix}.init", ElementId, JsonConvert.SerializeObject(_options), dotNetRef);
                _options.ResetChanged();
            }
            else
            {
                if (_options.CheckIsChanged())
                {
                    await JSRuntime.InvokeVoidAsync($"{Prefix}.sync", ElementId, JsonConvert.SerializeObject(_options), dotNetRef);
                    _options.ResetChanged();
                }
            }
        }

        public virtual async ValueTask DisposeAsync()
        {
            await JSRuntime.InvokeVoidAsync($"{Prefix}.dispose", ElementId, dotNetRef);
            dotNetRef.Dispose();
        }
    }
}
