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.Hardware.Videocards
{
    [Route(Navigation.Inventory.Hardware.Videocards.Hosts)]
    public partial class Hosts
    {
        [Parameter] public string? VideocardName { 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()
        {
            Breadcrumbs.Add(new BreadcrumbItem("Home", href: Navigation.Home));
            Breadcrumbs.Add(new BreadcrumbItem("Inventory", href: "#", true));
            Breadcrumbs.Add(new BreadcrumbItem("Videocards", href: Navigation.Inventory.Hardware.Videocards.Index));

            if (string.IsNullOrWhiteSpace(VideocardName))
            {
                Notification.Error(Snackbar, "Not Found");
                NavigationManager.NavigateTo(Navigation.Inventory.Hardware.Videocards.Index);
                return;
            }

            Title = $"Inventory » Videocards » {VideocardName} » Hosts｜Insight";
            Breadcrumbs.Add(new BreadcrumbItem(VideocardName, 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("driver", regex) |
                        Builders<BsonDocument>.Filter.Regex("date", regex);
                }

                var query = Database.HostVideocard()
                    .Aggregate()
                    .Match(Builders<HostVideocardEntity>.Filter.Regex(p => p.Name, new BsonRegularExpression(new Regex(VideocardName.Escape(), RegexOptions.IgnoreCase))))
                    .Lookup("host", "_host", "_id", "hosts")
                    .Match(new BsonDocument("hosts", new BsonDocument
                    {
                        { "$exists", true },
                        { "$ne", new BsonArray() }
                    }))
                    .Lookup("customer", "hosts._customer", "_id", "customers")
                    .Project(new BsonDocument
                    {
                        { "_id", 0 },
                        { "driver", 1 },
                        { "date", 1 },
                        { "host", new BsonDocument("$first", "$hosts") },
                        { "customer", new BsonDocument("$first", "$customers") },
                    })
                    .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"),
                            "Driver" => Builders<BsonDocument>.Sort.Ascending("driver"),
                            "Date" => Builders<BsonDocument>.Sort.Ascending("date"),
                            _ => null
                        },
                        SortDirection.Descending => state.SortLabel switch
                        {
                            "Customer" => Builders<BsonDocument>.Sort.Descending("customer.name"),
                            "Host" => Builders<BsonDocument>.Sort.Descending("host.name"),
                            "Driver" => Builders<BsonDocument>.Sort.Descending("driver"),
                            "Date" => Builders<BsonDocument>.Sort.Descending("date"),
                            _ => 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("driver")]
            public string? Driver { get; set; }

            [BsonElement("date")]
            public DateTime? Date { get; set; }

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

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