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

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

[Route(Navigation.Inventory.Systems.Os.Hosts)]
public partial class Hosts
{
    [Parameter] public string? OsName { get; set; }

    [Inject] private IMongoDatabase Database { get; init; } = default!;
    [Inject] private ISnackbar Snackbar { get; init; } = default!;
    [Inject] private NavigationManager NavigationManager { 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()
    {
        OsName = OsName.UriEscape(true);

        Breadcrumbs.Add(new BreadcrumbItem("Home", href: Navigation.Home));
        Breadcrumbs.Add(new BreadcrumbItem("Inventory", href: "#", true));
        Breadcrumbs.Add(new BreadcrumbItem("OS", href: Navigation.Inventory.Systems.Os.Index));

        if (string.IsNullOrWhiteSpace(OsName))
        {
            Notification.Error(Snackbar, "Not Found");
            NavigationManager.NavigateTo(Navigation.Inventory.Systems.Os.Index);
            return;
        }

        Title = $"Inventory » OS » {OsName} » Hosts｜Insight";
        Breadcrumbs.Add(new BreadcrumbItem(OsName, href: "#", true));
        Breadcrumbs.Add(new BreadcrumbItem("Hosts", 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("customer.name", regex) |
                    Builders<BsonDocument>.Filter.Regex("host.name", regex) |
                    Builders<BsonDocument>.Filter.Regex("version", regex);
            }

            var query = Database.HostOs()
                .Aggregate()
                .Match(Builders<HostOsEntity>.Filter.Eq(p => p.Name, OsName.Escape()))
                .Lookup("host", "_host", "_id", "hosts")
                .Match(new BsonDocument("hosts", new BsonDocument
                {
                    { "$exists", true },
                    { "$ne", new BsonArray() }
                }))
                .Lookup("customer", "hosts._customer", "_id", "customers")
                .Lookup("host_sys", "_host", "_host", "systems")
                .Project(new BsonDocument
                {
                    { "_id", 0 },
                    { "version", 1 },
                    { "host", new BsonDocument("$first", "$hosts") },
                    { "customer", new BsonDocument("$first", "$customers") },
                    { "systems", new BsonDocument("$first", "$systems") },
                })
                .Match(filter)
                .Sort(state.SortDirection switch
                {
                    SortDirection.Ascending => state.SortLabel switch
                    {
                        "Customer" => Builders<BsonDocument>.Sort.Ascending("customer.name"),
                        "Host" => Builders<BsonDocument>.Sort.Ascending("host.name"),
                        "Version" => Builders<BsonDocument>.Sort.Ascending("version"),
                        "License" => Builders<BsonDocument>.Sort.Ascending("license"),
                        _ => null
                    },
                    SortDirection.Descending => state.SortLabel switch
                    {
                        "Customer" => Builders<BsonDocument>.Sort.Descending("customer.name"),
                        "Host" => Builders<BsonDocument>.Sort.Descending("host.name"),
                        "Version" => Builders<BsonDocument>.Sort.Descending("version"),
                        "License" => Builders<BsonDocument>.Sort.Ascending("license"),
                        _ => null
                    },
                    _ => Builders<BsonDocument>.Sort.Ascending("customer.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)
        {
            Notification.Error(Snackbar);
            return new TableData<ViewModel>();
        }
    }

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

        [BsonElement("host")]
        public HostEntity? Hosts { get; set; }

        [BsonElement("customer")]
        public CustomerEntity? Customers { get; set; }

        [BsonElement("systems")]
        public HostSystemEntity? Systems { get; set; }
    }
}