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.Driver;
using MudBlazor;
using System.Text.RegularExpressions;
using SortDirection = MudBlazor.SortDirection;

namespace Insight.Web.Pages.Management.Hosts.Systems.StoragePools;

[Route(Navigation.Management.Hosts.Systems.StoragePools.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<HostStoragePoolEntity>? 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} » Storage Pools｜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("Storage Pools", href: "#", true));
    }

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

            if (string.IsNullOrWhiteSpace(Search) is false)
            {
                var regex = new BsonRegularExpression(new Regex(Search, RegexOptions.IgnoreCase));
                filter &= Builders<HostStoragePoolEntity>.Filter.Regex(x => x.Name, regex) |
                    Builders<HostStoragePoolEntity>.Filter.Regex(x => x.Resiliency, regex) |
                    Builders<HostStoragePoolEntity>.Filter.Regex(x => x.Size, regex) |
                    Builders<HostStoragePoolEntity>.Filter.Regex(x => x.AllocatedSize, regex) |
                    //Builders<HostStoragePoolEntity>.Filter.Regex(x => x.PhysicalDisks, regex) |
                    //Builders<HostStoragePoolEntity>.Filter.Regex(x => x.VirtualDisks, regex) |
                    Builders<HostStoragePoolEntity>.Filter.Regex(x => x.Health, regex);
            }

            var query = Database.HostStoragePool()
                .Aggregate()
                .Match(filter)
                .Lookup<HostStoragePoolEntity, HostStoragePoolPhysicalDiskEntity, HostStoragePoolEntity>(Database.HostStoragePoolPhysicalDisk(), p => p.Id, p => p.StoragePool, p => p.PhysicalDisks)
                .Lookup<HostStoragePoolEntity, HostStoragePoolVirtualDiskEntity, HostStoragePoolEntity>(Database.HostStoragePoolVirtualDisk(), p => p.Id, p => p.StoragePool, p => p.VirtualDisks)
                .Sort(state.SortDirection switch
                {
                    SortDirection.Ascending => state.SortLabel switch
                    {
                        "Name" => Builders<HostStoragePoolEntity>.Sort.Ascending(p => p.Name),
                        "Health" => Builders<HostStoragePoolEntity>.Sort.Ascending(p => p.Health),
                        "Resiliency" => Builders<HostStoragePoolEntity>.Sort.Ascending(p => p.Resiliency),
                        "Size" => Builders<HostStoragePoolEntity>.Sort.Ascending(p => p.Size),
                        "AllocatedSize" => Builders<HostStoragePoolEntity>.Sort.Ascending(p => p.AllocatedSize),
                        "PhysicalDisks" => Builders<HostStoragePoolEntity>.Sort.Ascending(p => p.PhysicalDisks),
                        "VirtualDisks" => Builders<HostStoragePoolEntity>.Sort.Ascending(p => p.VirtualDisks),
                        _ => null
                    },
                    SortDirection.Descending => state.SortLabel switch
                    {
                        "Name" => Builders<HostStoragePoolEntity>.Sort.Descending(p => p.Name),
                        "Health" => Builders<HostStoragePoolEntity>.Sort.Descending(p => p.Health),
                        "Resiliency" => Builders<HostStoragePoolEntity>.Sort.Descending(p => p.Resiliency),
                        "Size" => Builders<HostStoragePoolEntity>.Sort.Descending(p => p.Size),
                        "AllocatedSize" => Builders<HostStoragePoolEntity>.Sort.Descending(p => p.AllocatedSize),
                        "PhysicalDisks" => Builders<HostStoragePoolEntity>.Sort.Descending(p => p.PhysicalDisks),
                        "VirtualDisks" => Builders<HostStoragePoolEntity>.Sort.Descending(p => p.VirtualDisks),
                        _ => null
                    },
                    _ => Builders<HostStoragePoolEntity>.Sort.Ascending(p => p.Name)
                });

            var countResult = await query.Count().FirstOrDefaultAsync(default);

            return new TableData<HostStoragePoolEntity>()
            {
                TotalItems = countResult is null ? 0 : (int)countResult.Count,
                Items = await query.Skip(state.Page * state.PageSize).Limit(state.PageSize).ToListAsync(default)
            };
        }
        catch (Exception)
        {
            Notification.Error(Snackbar);
            return new TableData<HostStoragePoolEntity>();
        }
    }
}