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

namespace Insight.Web.Pages.Management.Agents;

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

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

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

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

        if (string.IsNullOrWhiteSpace(AgentId) || ObjectId.TryParse(AgentId, out var agentId) is false)
        {
            Notification.Error(Snackbar, "Not Found");
            NavigationManager.NavigateTo(Navigation.Management.Agents.Index);
            return;
        }

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

        StateHasChanged();

        _agent = await Database.Agent()
            .Aggregate()
            .Match(Builders<AgentEntity>.Filter.Eq(p => p.Id, AgentId))
            .Lookup<AgentEntity, HostEntity, AgentEntity>(Database.Host(), p => p.Id, p => p.Agent, p => p.Hosts)
            .FirstOrDefaultAsync(default);

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

        _title = $"Agent » {_agent.Hostname}｜Insight";
        _breadcrumbs.Add(new BreadcrumbItem(_agent.Hostname, href: "#", true));

        StateHasChanged();

        _logs = await Database.AgentLog()
            .CountDocumentsAsync(Builders<AgentLogEntity>
            .Filter.Eq(p => p.Agent, _agent.Id));

        StateHasChanged();
    }

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