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.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.Hardware.Memory;

[Route(Navigation.Inventory.Hardware.Memory.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 » Memory｜Insight";
        Breadcrumbs.Add(new BreadcrumbItem("Home", href: Navigation.Home));
        Breadcrumbs.Add(new BreadcrumbItem("Inventory", href: "#", true));
        Breadcrumbs.Add(new BreadcrumbItem("Memory", href: "#", true));
    }

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

            if (string.IsNullOrWhiteSpace(Search) is false)
            {
                var regex = new BsonRegularExpression(new Regex(Search, RegexOptions.IgnoreCase));
                filter &= Builders<HostMemoryEntity>.Filter.Regex(x => x.Company, regex) |
                    Builders<HostMemoryEntity>.Filter.Regex(x => x.Name, regex);
            }

            var query = Database.HostMemory()
                .Aggregate()
                .Match(filter)
                .Lookup("host", "_host", "_id", "hosts")
                .Match(new BsonDocument("hosts", new BsonDocument
                {
                    { "$exists", true },
                    { "$ne", new BsonArray() }
                }))
                .Group(new BsonDocument
                {
                    { "_id", new BsonDocument("name", "$name") },
                    { "company", new BsonDocument("$first", "$company") },
                    { "name", new BsonDocument("$first", "$name") },
                    { "hosts", new BsonDocument("$addToSet", "$hosts") },
                })
                .Project(new BsonDocument
                {
                    { "_id", 0 },
                    { "company", 1 },
                    { "name", 1 },
                    { "hosts", 1 },
                    { "hosts_size", new BsonDocument("$size", "$hosts") },
                })
                .Sort(state.SortDirection switch
                {
                    SortDirection.Ascending => state.SortLabel switch
                    {
                        "Company" => Builders<BsonDocument>.Sort.Ascending("company"),
                        "Name" => Builders<BsonDocument>.Sort.Ascending("name"),
                        "Hosts" => Builders<BsonDocument>.Sort.Ascending("hosts_size"),
                        _ => null
                    },
                    SortDirection.Descending => state.SortLabel switch
                    {
                        "Company" => Builders<BsonDocument>.Sort.Descending("company"),
                        "Name" => Builders<BsonDocument>.Sort.Descending("name"),
                        "Hosts" => Builders<BsonDocument>.Sort.Descending("hosts_size"),
                        _ => null
                    },
                    _ => Builders<BsonDocument>.Sort.Descending("hosts_size")
                });

            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)
        {
            Notification.Error(Snackbar);
            return new TableData<ViewModel>();
        }
    }

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

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

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