@using System.Collections.Concurrent;
@using Vaitr.Bus;
@using static Insight.Web.Constants.Events.Chat;

@inherits ComponentBase
@implements IDisposable

@inject Bus Bus
@inject SessionHandler SessionHandler

<AuthorizeView>
    <Authorized>
        <MudIconButton OnClick="()=>_chatDialog?.Toggle()" Icon="@(_chatDialog?.NewMessages > 0 ? Icons.Material.Filled.MarkUnreadChatAlt : Icons.Material.Filled.Chat)" Color="Color.Inherit" />
        <ChatDialog @ref="_chatDialog" />
    </Authorized>
</AuthorizeView>

@code {
    private ChatDialog? _chatDialog;
    private bool _disposed;

    private readonly ConcurrentBag<IDisposable> _subscriptions = new();

    protected override void OnInitialized()
    {
        _subscriptions.Add(Bus.SubscribeAsync<string>(async (x, c) => await InvokeAsync(StateHasChanged), p => p == Events.Sessions.Changed));
        _subscriptions.Add(Bus.SubscribeAsync<ChatMessageReceived>(async (x, c) => await InvokeAsync(StateHasChanged), p => p.Message.SenderId != SessionHandler.State.Uid));
    }

    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }

    private void Dispose(bool disposing)
    {
        // auto disposed when starved circuit timeouts (disconnects)

        if (_disposed is false) return;
        if (disposing is false) return;

        try
        {
            foreach (var sub in _subscriptions) sub.Dispose();
            _subscriptions.Clear();
        }
        finally
        {
            _disposed = true;
        }
    }
}