using Insight.Infrastructure;
using Insight.Web.Constants;
using Microsoft.AspNetCore.Components;
using MongoDB.Driver;
using Vaitr.Bus;

namespace Insight.Web.Components.Navbars;

public partial class Customer
{
    [CascadingParameter] public IReadOnlyDictionary<string, object>? RouteValues { get; set; }

    [Inject] private IMongoDatabase Database { get; set; } = default!;
    [Inject] private Bus Bus { get; init; } = default!;

    private string Title { get; set; } = "Customer";
    private string? Id { get; set; }

    private IDisposable? Token { get; set; }
    public bool Disposed { get; set; } = false;

    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;

        Token?.Dispose();
    }
}