using Insight.Infrastructure;
using Insight.Web.Components.Containers;
using Insight.Web.Constants;
using Microsoft.AspNetCore.Components;
using MongoDB.Bson;
using MongoDB.Bson.Serialization;
using MongoDB.Bson.Serialization.Attributes;
using MongoDB.Driver;
using MudBlazor;
using System.Text.RegularExpressions;
using SortDirection = MudBlazor.SortDirection;

namespace Insight.Web.Pages.Inventory.Systems.Os;

[Route(Navigation.Inventory.Systems.Os.Index)]
public partial class Index
{
    [Inject] private IMongoDatabase Database { get; init; } = default!;
    [Inject] private ISnackbar Snackbar { get; init; } = default!;

    private TableContainer<ViewModel>? Container { get; set; }
    private string Title { get; set; } = Global.Name;
    private List<BreadcrumbItem> Breadcrumbs { get; } = new();
    private string? Search { get; set; }

    protected override void OnInitialized()
    {
        Title = $"Inventory » OS｜Insight";
        Breadcrumbs.Add(new BreadcrumbItem("Home", href: Navigation.Home));
        Breadcrumbs.Add(new BreadcrumbItem("Inventory", href: "#", true));
        Breadcrumbs.Add(new BreadcrumbItem("OS", href: "#", true));
    }

    private async Task<TableData<ViewModel>> LoadDataAsync(TableState state)
    {
        try
        {
            var filter = Builders<BsonDocument>.Filter.Empty;

            if (string.IsNullOrWhiteSpace(Search) is false)
            {
                var regex = new BsonRegularExpression(new Regex(Search, RegexOptions.IgnoreCase));
                filter &= Builders<BsonDocument>.Filter.Regex("name", regex);
            }

            var query = Database.HostOs()
                .Aggregate()
                .AppendStage<BsonDocument>(new BsonDocument("$unionWith", new BsonDocument
                {
                    { "coll", "host_hv_vm" },
                    { "pipeline", new BsonArray
                    {
                        new BsonDocument("$match", new BsonDocument("$expr",
                        new BsonDocument("$ne", new BsonArray
                        {
                            "guest_os", BsonNull.Value
                        }))),
                        new BsonDocument("$project", new BsonDocument
                        {
                            { "_id", 0 },
                            { "name", "$guest_os" }
                        })
                    }}
                }))
                .Project(new BsonDocument
                {
                    { "_id", 0 },
                    { "name", "$name" }
                })
                .Group(new BsonDocument("_id", "$name"))
                .Match(new BsonDocument("_id", new BsonDocument("$ne", BsonNull.Value)))
                .Lookup("host_os", "_id", "name", "hosts_os")
                .Lookup("host_hv_vm", "_id", "guest_os", "guests_os")
                .Lookup("host", "hosts_os._host", "_id", "hosts")
                .Lookup("host", "guests_os._host", "_id", "guests")
                .Project(new BsonDocument
                {
                    { "_id", 0 },
                    { "name", "$_id" },
                    { "host_size", new BsonDocument("$size", "$hosts") },
                    { "guest_size", new BsonDocument("$size", "$guests") }
                })
                .Match(filter)
                .Sort(state.SortDirection switch
                {
                    SortDirection.Ascending => state.SortLabel switch
                    {
                        "Name" => Builders<BsonDocument>.Sort.Ascending("name"),
                        "Hosts" => Builders<BsonDocument>.Sort.Ascending("host_size"),
                        "Guests" => Builders<BsonDocument>.Sort.Ascending("guest_size"),
                        _ => null
                    },
                    SortDirection.Descending => state.SortLabel switch
                    {
                        "Name" => Builders<BsonDocument>.Sort.Descending("name"),
                        "Hosts" => Builders<BsonDocument>.Sort.Descending("host_size"),
                        "Guests" => Builders<BsonDocument>.Sort.Descending("guest_size"),
                        _ => null
                    },
                    _ => Builders<BsonDocument>.Sort.Ascending("name")
                });

            var countResult = await query.Count().FirstOrDefaultAsync(default);
            var itemResult = await query.Skip(state.Page * state.PageSize).Limit(state.PageSize).ToListAsync(default);

            return new TableData<ViewModel>()
            {
                TotalItems = countResult is null ? 0 : (int)countResult.Count,
                Items = itemResult.Select(x => BsonSerializer.Deserialize<ViewModel>(x))
            };
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.ToString());

            Notification.Error(Snackbar);
            return new TableData<ViewModel>();
        }
    }

    [BsonIgnoreExtraElements]
    public class ViewModel
    {
        [BsonElement("name")]
        public string? Name { get; set; }

        [BsonElement("host_size")]
        public int? Hosts { get; set; }

        [BsonElement("guest_size")]
        public int? Guests { get; set; }
    }
}