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

namespace Insight.Web.Pages.Management.Scheduler.Jobs;

[Route(Navigation.Management.Scheduler.Jobs.Details)]
public partial class Details
{
    [Parameter] public string? JobId { 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 List<BreadcrumbItem> Breadcrumbs { get; } = new();
    private JobEntity? Job { get; set; }

    private async Task LoadDataAsync()
    {
        Breadcrumbs.Clear();
        Job = null;

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

        Breadcrumbs.Add(new BreadcrumbItem("Home", href: Navigation.Home));
        Breadcrumbs.Add(new BreadcrumbItem("Scheduler", href: Navigation.Management.Scheduler.Index));
        Breadcrumbs.Add(new BreadcrumbItem("Jobs", href: Navigation.Management.Scheduler.Jobs.Index));

        StateHasChanged();

        Job = await Database.Job()
            .Aggregate()
            .Match(Builders<JobEntity>.Filter.Eq(p => p.Id, JobId))
            //.Lookup<CustomerEntity, HostEntity, CustomerEntity>(Database.Host(), p => p.Id, p => p.Customer, p => p.Hosts)
            .FirstOrDefaultAsync(default);

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

        Title = $"Job » {Job.Name ?? Job.Id}｜Insight";
        Breadcrumbs.Add(new BreadcrumbItem(Job.Name ?? Job.Id, href: "#", true));

        StateHasChanged();
    }
}