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.Monitoring.Maintenance.Snapshots;

[Route(Navigation.Monitoring.Maintenance.Snapshots.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 = $"Monitoring » Maintenance » Snapshots｜Insight";
        Breadcrumbs.Add(new BreadcrumbItem("Home", href: Navigation.Home));
        Breadcrumbs.Add(new BreadcrumbItem("Monitoring", href: Navigation.Monitoring.Index));
        Breadcrumbs.Add(new BreadcrumbItem("Maintenance", href: Navigation.Monitoring.Maintenance.Index));
        Breadcrumbs.Add(new BreadcrumbItem("Snapshots", 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("virtualmaschine.name", regex) |
                    Builders<BsonDocument>.Filter.Regex("name", regex) |
                    Builders<BsonDocument>.Filter.Regex("notes", regex);
            }

            var query = Database.HostVirtualMaschineConfig().Aggregate()
                .Lookup("host_hv_vm", "virtualmaschine", "_id", "virtualmaschines")
                .Project(new BsonDocument
                {
                    { "_id", 1 },
                    { "uniqueid", 1 },
                    { "host", 1 },
                    { "name", 1 },
                    { "notes", 1 },
                    { "creationtime", 1 },
                    { "virtualmaschine", new BsonDocument("$first", "$virtualmaschines") }
                })
                .Match(new BsonDocument("$expr", new BsonDocument("$ne", new BsonArray
                {
                    "$uniqueid",
                    "$virtualmaschine.uniqueid"
                })))
                .Lookup("host", "host", "_id", "hosts")
                .Match(new BsonDocument("hosts", new BsonDocument("$exists", new BsonDocument("$ne", BsonNull.Value))))
                .Lookup("customer", "hosts._customer", "_id", "customers")
                .Project(new BsonDocument
                {
                    { "_id", 1 },
                    { "host", new BsonDocument("$first", "$hosts") },
                    { "customer", new BsonDocument("$first", "$customers") },
                    { "uniqueid", 1 },
                    { "name", 1 },
                    { "notes", 1 },
                    { "creationtime", 1 },
                    { "virtualmaschine", 1 }
                })
                .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"),
                        "VirtualMaschine" => Builders<BsonDocument>.Sort.Ascending("virtualmaschine.name"),
                        "Name" => Builders<BsonDocument>.Sort.Ascending("name"),
                        "Notes" => Builders<BsonDocument>.Sort.Ascending("notes"),
                        "CreationTime" => Builders<BsonDocument>.Sort.Ascending("creationtime"),
                        _ => null
                    },
                    SortDirection.Descending => state.SortLabel switch
                    {
                        "Customer" => Builders<BsonDocument>.Sort.Descending("customer.name"),
                        "Host" => Builders<BsonDocument>.Sort.Descending("host.name"),
                        "VirtualMaschine" => Builders<BsonDocument>.Sort.Descending("virtualmaschine.name"),
                        "Name" => Builders<BsonDocument>.Sort.Descending("name"),
                        "Notes" => Builders<BsonDocument>.Sort.Descending("notes"),
                        "CreationTime" => Builders<BsonDocument>.Sort.Descending("creationtime"),
                        _ => null
                    },
                    _ => Builders<BsonDocument>.Sort.Ascending("creationtime")
                });

            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
    {
        [BsonId]
        public ObjectId? Id { get; set; }

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

        [BsonElement("notes")]
        public string? Notes { get; set; }

        [BsonElement("creationtime")]
        public DateTime? CreationTime { get; set; }

        [BsonElement("virtualmaschine")]
        public HostHypervisorVirtualMaschineEntity? VirtualMaschine { get; set; }

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

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