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

namespace Insight.Web.Pages.Management.Hosts.Systems.Os;

[Route(Navigation.Management.Hosts.Systems.Os.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 string Title { get; set; } = Global.Name;
    private readonly List<BreadcrumbItem> _breadcrumbs = new();
    private HostOsEntity? HostOs { get; set; }

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

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

        StateHasChanged();

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

        var host = await Database.Host()
            .Find(Builders<HostEntity>
            .Filter
            .Eq(p => p.Id, HostId))
            .FirstOrDefaultAsync(default);

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

        Title = $"Hosts » {host.Name} » Os｜Insight";

        _breadcrumbs.Add(new BreadcrumbItem(host.Name, href: Navigation.Management.Hosts.DetailsHref(HostId)));
        _breadcrumbs.Add(new BreadcrumbItem("Operation System", href: "#", true));

        StateHasChanged();

        HostOs = await Database.HostOs()
            .Find(Builders<HostOsEntity>
            .Filter
            .Eq(p => p.Host, HostId))
            .FirstOrDefaultAsync();

        StateHasChanged();
    }
}