@using MongoDB.Driver
@using Vaitr.Bus

@inherits ComponentBase
@implements IDisposable

@inject IMongoDatabase Database
@inject Bus Bus

<MudNavLink Href=@Navigation.Management.Customers.DetailsHref(_id) Icon="@Icons.Material.Outlined.Business" IconColor="Color.Inherit" Match="NavLinkMatch.All" Class="pl-3">
    @_title
</MudNavLink>

<div class="mt-3">
    <MudNavLink Href=@Navigation.Management.Customers.HostsHref(_id) Match="NavLinkMatch.All">Hosts</MudNavLink>
</div>

@code{
    [CascadingParameter] public IReadOnlyDictionary<string, object>? RouteValues { get; set; }

    private string? _id;
    private string _title = "Customer";
    private IDisposable? _token;
    private bool _disposed;

    protected override void OnInitialized()
    {
        _token = Bus.Subscribe<string>(OnRefresh, p => p == Events.Layout.Rendered);
    }

    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        if (RouteValues is not null && _id is null)
        {
            if (RouteValues.TryGetValue("customerId", out object? rawId) == false) return;
            _id = rawId?.ToString();

            var entity = await Database.Customer()
                .Find(p => p.Id == _id)
                .FirstOrDefaultAsync(default);

            _title = $"{entity?.Name}";

            await InvokeAsync(() => StateHasChanged());
        }
    }

    public void OnRefresh(string? message) => InvokeAsync(StateHasChanged);

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

    private void Dispose(bool disposing)
    {
        if (_disposed) return;
        if (disposing is false) return;

        try
        {
            _token?.Dispose();
        }
        finally
        {
            _disposed = true;
        }
    }
}