using Microsoft.JSInterop;
using Newtonsoft.Json;

namespace FNZCM.BlazorWasm.UI.Components.FnzBootstrap.Bases
{
    public class FnzBootstrapComponentBase<T, TOptions> : FnzComponentBase
        where T : class
        where TOptions : OptionsBase, new()
    {
        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 override async ValueTask DisposeAsync()
        {
            await JSRuntime.InvokeVoidAsync($"{Prefix}.dispose", ElementId, DotNetRef);
            await base.DisposeAsync();
        }
    }
}
