using Insight.Infrastructure;
using Insight.Infrastructure.Entities;
using Insight.Web.Components.Containers;
using Insight.Web.Constants;
using Microsoft.AspNetCore.Components;
using MongoDB.Driver;
using MudBlazor;

namespace Insight.Web.Pages.Management.Hosts;

[Route(Navigation.Management.Hosts.Details)]
public partial class Details
{
    [Parameter] public string? HostId { get; set; }

    [Inject] private IMongoDatabase Database { get; init; } = default!;
    [Inject] private ISnackbar Snackbar { get; init; } = default!;
    [Inject] private NavigationManager NavigationManager { get; init; } = default!;

    private BaseContainer? _container;
    private string _title = Global.Name;
    private readonly List<BreadcrumbItem> _breadcrumbs = new();

    private HostEntity? _host;
    private HostOsEntity? _os;
    private HostSystemEntity? _system;
    private long? _logs;

    private async Task LoadDataAsync()
    {
        _breadcrumbs.Clear();
        _host = null;
        _logs = null;

        _breadcrumbs.Add(new BreadcrumbItem("Home", href: Navigation.Home));
        _breadcrumbs.Add(new BreadcrumbItem("Hosts", href: Navigation.Management.Hosts.Index));

        StateHasChanged();

        if (string.IsNullOrWhiteSpace(HostId))
        {
            Notification.Error(Snackbar, "Not Found");
            NavigationManager.NavigateTo(Navigation.Management.Hosts.Index);
            return;
        }

        _host = await Database.Host()
            .Aggregate()
            .Match(Builders<HostEntity>.Filter.Eq(p => p.Id, HostId))
            .Lookup<HostEntity, CustomerEntity, HostEntity>(Database.Customer(), p => p.Customer, p => p.Id, p => p.Customers)
            .Lookup<HostEntity, AgentEntity, HostEntity>(Database.Agent(), p => p.Agent, p => p.Id, p => p.Agents)
            .FirstOrDefaultAsync(default);

        if (_host is null)
        {
            Notification.Error(Snackbar, "Not Found");
            NavigationManager.NavigateTo(Navigation.Management.Hosts.Index);
            return;
        }

        _title = $"Hosts » {_host.Name} » Logs｜Insight";
        _breadcrumbs.Add(new BreadcrumbItem(_host.Name, href: "#", true));

        StateHasChanged();

        _os = await Database.HostOs()
            .Aggregate()
            .Match(Builders<HostOsEntity>.Filter.Eq(p => p.Host, HostId))
            .FirstOrDefaultAsync(default);

        StateHasChanged();

        _system = await Database.HostSystem()
            .Aggregate()
            .Match(Builders<HostSystemEntity>.Filter.Eq(p => p.Host, HostId))
            .FirstOrDefaultAsync(default);

        StateHasChanged();

        _logs = await Database.HostLog()
            .CountDocumentsAsync(Builders<HostLogEntity>
            .Filter.Eq(p => p.Host, _host.Id));

        StateHasChanged();
    }

    private async Task OnRefreshAsync()
    {
        if (_container is null) return;
        await LoadDataAsync();
    }
}