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

namespace Insight.Web.Components.Navbars;

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

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

    private CustomerEntity? CustomerEntity { get; set; }
    private HostEntity HostEntity { get; set; }
    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("hostId", out object? rawId) == false) return;
            Id = rawId?.ToString();

            HostEntity = await Database.Host()
                .Find(p => p.Id == Id)
                .FirstOrDefaultAsync(default);

            if (HostEntity is not null)
            {
                CustomerEntity = await Database.Customer()
                    .Find(p => p.Id == HostEntity.Customer)
                    .FirstOrDefaultAsync(default);
            }

            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();
    }
}
