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.Management.Hosts.Systems.VirtualMaschines;

[Route(Navigation.Management.Hosts.Systems.VirtualMaschines.Index)]
public partial class Index
{
    [Parameter] public string? HostId { 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 async Task OnInitializedAsync()
    {
        if (string.IsNullOrWhiteSpace(HostId) || ObjectId.TryParse(HostId, out var hostId) is false)
        {
            Notification.Error(Snackbar, "Not Found");
            NavigationManager.NavigateTo(Navigation.Management.Hosts.Index);
            return;
        }

        var host = await Database.Host()
            .Find(Builders<HostEntity>
            .Filter
            .Eq(p => p.Id, HostId))
            .FirstOrDefaultAsync(default);

        if (host is null)
        {
            Notification.Error(Snackbar, "Not Found");
            NavigationManager.NavigateTo(Navigation.Management.Hosts.Index);
            return;
        }

        Title = $"Hosts » {host.Name} » Virtual Maschines｜Insight";
        Breadcrumbs.Add(new BreadcrumbItem("Home", href: Navigation.Home));
        Breadcrumbs.Add(new BreadcrumbItem("Hosts", href: Navigation.Management.Hosts.Index));
        Breadcrumbs.Add(new BreadcrumbItem(host.Name, href: Navigation.Management.Hosts.DetailsHref(HostId)));
        Breadcrumbs.Add(new BreadcrumbItem("Virtual Maschines", href: "#", true));
    }

    private async Task<TableData<ViewModel>> LoadDataAsync(TableState state)
    {
        try
        {
            var filter = Builders<HostHypervisorVirtualMaschineEntity>.Filter.Eq(p => p.Host, HostId);
            var search = Builders<BsonDocument>.Filter.Empty;

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

            var query = Database.HostHypervisorVirtualMaschine()
                .Aggregate()
                .Match(filter)
                .Lookup("host", "_host", "_id", "hosts")
                .Match(new BsonDocument("hosts", new BsonDocument
                {
                    { "$exists", true },
                    { "$ne", new BsonArray() }
                }))
                .AppendStage<BsonDocument>(new BsonDocument("$addFields", new BsonDocument
                {
                    { "host", new BsonDocument("$first", "$hosts") }
                }))
                .Lookup("customer", "host._customer", "_id", "customers")
                .AppendStage<BsonDocument>(new BsonDocument("$addFields", new BsonDocument
                {
                    { "customer", new BsonDocument("$first", "$customers") }
                }))
                .Lookup("host_hv_vm_cfg", "_id", "virtualmaschine", "snapshots")
                .Project(new BsonDocument
                {
                    { "_id", 1 },
                    { "host", 1 },
                    { "customer", 1 },
                    { "name", 1 },
                    { "version_configuration", 1 },
                    { "guest_os", 1 },
                    { "enabled", 1 },
                    { "health", 1 },
                    { "snapshots_count", new BsonDocument("$subtract", new BsonArray
                        {
                            new BsonDocument("$size", "$snapshots"), 1
                        })
                    }
                })
                .Match(search)
                .Sort(state.SortDirection switch
                {
                    SortDirection.Ascending => state.SortLabel switch
                    {
                        "Name" => Builders<BsonDocument>.Sort.Ascending("name"),
                        "ConfigurationVersion" => Builders<BsonDocument>.Sort.Ascending("version_configuration"),
                        "GuestOperatingSystem" => Builders<BsonDocument>.Sort.Ascending("guest_os"),
                        "Snapshots" => Builders<BsonDocument>.Sort.Ascending("snapshots_count"),
                        "Enabled" => Builders<BsonDocument>.Sort.Ascending("enabled"),
                        "HealthState" => Builders<BsonDocument>.Sort.Ascending("health"),
                        _ => null
                    },
                    SortDirection.Descending => state.SortLabel switch
                    {
                        "Name" => Builders<BsonDocument>.Sort.Descending("name"),
                        "ConfigurationVersion" => Builders<BsonDocument>.Sort.Descending("version_configuration"),
                        "GuestOperatingSystem" => Builders<BsonDocument>.Sort.Descending("guest_os"),
                        "Snapshots" => Builders<BsonDocument>.Sort.Descending("snapshots_count"),
                        "Enabled" => Builders<BsonDocument>.Sort.Descending("enabled"),
                        "HealthState" => Builders<BsonDocument>.Sort.Descending("health"),
                        _ => 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)
        {
            Notification.Error(Snackbar);
            return new TableData<ViewModel>();
        }
    }

    [BsonIgnoreExtraElements]
    public class ViewModel
    {
        [BsonId]
        public ObjectId? Id { get; set; }

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

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

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

        [BsonElement("version_configuration")]
        public string? Configuration { get; set; }

        [BsonElement("guest_os")]
        public string? GuestOs { get; set; }

        [BsonElement("enabled")]
        public string? Enabled { get; set; }

        [BsonElement("health")]
        public string? Health { get; set; }

        [BsonElement("snapshots_count")]
        public int? Snapshots { get; set; }
    }
}