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.VirtualDisks;

[Route(Navigation.Management.Hosts.Systems.StoragePools.VirtualDisks.Index)]
public partial class Index
{
    [Parameter] public string? HostId { get; set; }
    [Parameter] public string? StoragePoolId { get; set; }

    [Inject] private IMongoDatabase Database { get; set; } = default!;
    [Inject] private ISnackbar Snackbar { get; init; } = default!;
    [Inject] private NavigationManager NavigationManager { get; init; } = default!;

    private TableContainer<HostStoragePoolVirtualDiskEntity>? 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;
        }

        if (string.IsNullOrWhiteSpace(StoragePoolId) || ObjectId.TryParse(StoragePoolId, out var storagePoolId) is false)
        {
            Notification.Error(Snackbar, "Not Found");
            NavigationManager.NavigateTo(Navigation.Management.Hosts.Systems.StoragePools.IndexHref(HostId));
            return;
        }

        var storagePool = await Database.HostStoragePool()
                .Find(p => p.Host == HostId && p.Id == StoragePoolId)
                .FirstOrDefaultAsync();

        if (storagePool is null)
        {
            Notification.Error(Snackbar, "Not Found");
            NavigationManager.NavigateTo(Navigation.Management.Hosts.Systems.StoragePools.IndexHref(HostId));
            return;
        }

        Title = $"Hosts » {host.Name} » Storage Pools » {storagePool.Name} » Virtual Disks｜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: Navigation.Management.Hosts.Systems.StoragePools.IndexHref(HostId)));
        Breadcrumbs.Add(new BreadcrumbItem(storagePool.Name, href: Navigation.Management.Hosts.Systems.StoragePools.DetailsHref(HostId, StoragePoolId)));
        Breadcrumbs.Add(new BreadcrumbItem("Virtual Disks", href: "#", true));
    }

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

            if (string.IsNullOrWhiteSpace(Search) is false)
            {
                var regex = new BsonRegularExpression(new Regex(Search, RegexOptions.IgnoreCase));
                filter &= Builders<HostStoragePoolVirtualDiskEntity>.Filter.Regex(x => x.Name, regex);
            }

            var query = Database.HostStoragePoolVirtualDisk()
                .Find(filter)
                .Sort(state.SortDirection switch
                {
                    SortDirection.Ascending => state.SortLabel switch
                    {
                        "Name" => Builders<HostStoragePoolVirtualDiskEntity>.Sort.Ascending(p => p.Name),
                        "Provisioning" => Builders<HostStoragePoolVirtualDiskEntity>.Sort.Ascending(p => p.Provisioning),
                        "Resiliency" => Builders<HostStoragePoolVirtualDiskEntity>.Sort.Ascending(p => p.Resiliency),
                        "Size" => Builders<HostStoragePoolVirtualDiskEntity>.Sort.Ascending(p => p.Size),
                        "AllocatedSize" => Builders<HostStoragePoolVirtualDiskEntity>.Sort.Ascending(p => p.AllocatedSize),
                        "Footprint" => Builders<HostStoragePoolVirtualDiskEntity>.Sort.Ascending(p => p.Footprint),
                        "ReadCache" => Builders<HostStoragePoolVirtualDiskEntity>.Sort.Ascending(p => p.ReadCacheSize),
                        "WriteCache" => Builders<HostStoragePoolVirtualDiskEntity>.Sort.Ascending(p => p.WriteCacheSize),
                        "Redundancy" => Builders<HostStoragePoolVirtualDiskEntity>.Sort.Ascending(p => p.PhysicalRedundancy),
                        "HealthStatus" => Builders<HostStoragePoolVirtualDiskEntity>.Sort.Ascending(p => p.Health),
                        _ => null
                    },
                    SortDirection.Descending => state.SortLabel switch
                    {
                        "Name" => Builders<HostStoragePoolVirtualDiskEntity>.Sort.Descending(p => p.Name),
                        "Provisioning" => Builders<HostStoragePoolVirtualDiskEntity>.Sort.Descending(p => p.Provisioning),
                        "Resiliency" => Builders<HostStoragePoolVirtualDiskEntity>.Sort.Descending(p => p.Resiliency),
                        "Size" => Builders<HostStoragePoolVirtualDiskEntity>.Sort.Descending(p => p.Size),
                        "AllocatedSize" => Builders<HostStoragePoolVirtualDiskEntity>.Sort.Descending(p => p.AllocatedSize),
                        "Footprint" => Builders<HostStoragePoolVirtualDiskEntity>.Sort.Descending(p => p.Footprint),
                        "ReadCache" => Builders<HostStoragePoolVirtualDiskEntity>.Sort.Descending(p => p.ReadCacheSize),
                        "WriteCache" => Builders<HostStoragePoolVirtualDiskEntity>.Sort.Descending(p => p.WriteCacheSize),
                        "Redundancy" => Builders<HostStoragePoolVirtualDiskEntity>.Sort.Descending(p => p.PhysicalRedundancy),
                        "HealthStatus" => Builders<HostStoragePoolVirtualDiskEntity>.Sort.Descending(p => p.Health),
                        _ => null
                    },
                    _ => Builders<HostStoragePoolVirtualDiskEntity>.Sort.Ascending(p => p.Name)
                });

            return new TableData<HostStoragePoolVirtualDiskEntity>()
            {
                TotalItems = (int)await query.CountDocumentsAsync(default),
                Items = await query.Skip(state.Page * state.PageSize).Limit(state.PageSize).ToListAsync(default)
            };
        }
        catch (Exception)
        {
            Notification.Error(Snackbar);
            return new TableData<HostStoragePoolVirtualDiskEntity>();
        }
    }
}