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.Hardware.Memory;

[Route(Navigation.Management.Hosts.Hardware.Memory.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<HostMemoryEntity>? 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} » Memory｜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("Memory", href: "#", true));
    }

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

            if (string.IsNullOrWhiteSpace(Search) is false)
            {
                var regex = new BsonRegularExpression(new Regex(Search, RegexOptions.IgnoreCase));
                filter &= Builders<HostMemoryEntity>.Filter.Regex(x => x.Index, regex) |
                    Builders<HostMemoryEntity>.Filter.Regex(x => x.Company, regex) |
                    Builders<HostMemoryEntity>.Filter.Regex(x => x.Name, regex) |
                    Builders<HostMemoryEntity>.Filter.Regex(x => x.Tag, regex) |
                    Builders<HostMemoryEntity>.Filter.Regex(x => x.Location, regex) |
                    Builders<HostMemoryEntity>.Filter.Regex(x => x.Serial, regex) |
                    Builders<HostMemoryEntity>.Filter.Regex(x => x.Capacity, regex) |
                    Builders<HostMemoryEntity>.Filter.Regex(x => x.Clock, regex) |
                    Builders<HostMemoryEntity>.Filter.Regex(x => x.CurrentClock, regex) |
                    Builders<HostMemoryEntity>.Filter.Regex(x => x.Voltage, regex) |
                    Builders<HostMemoryEntity>.Filter.Regex(x => x.CurrentVoltage, regex);
            }

            var query = Database.HostMemory()
                .Find(filter)
                .Sort(state.SortDirection switch
                {
                    SortDirection.Ascending => state.SortLabel switch
                    {
                        "Company" => Builders<HostMemoryEntity>.Sort.Ascending(p => p.Company),
                        "Name" => Builders<HostMemoryEntity>.Sort.Ascending(p => p.Name),
                        "Tag" => Builders<HostMemoryEntity>.Sort.Ascending(p => p.Tag),
                        "Location" => Builders<HostMemoryEntity>.Sort.Ascending(p => p.Location),
                        "Serial" => Builders<HostMemoryEntity>.Sort.Ascending(p => p.Serial),
                        "Capacity" => Builders<HostMemoryEntity>.Sort.Ascending(p => p.Capacity),
                        "Clock" => Builders<HostMemoryEntity>.Sort.Ascending(p => p.Clock),
                        "Voltage" => Builders<HostMemoryEntity>.Sort.Ascending(p => p.Voltage),
                        _ => null
                    },
                    SortDirection.Descending => state.SortLabel switch
                    {
                        "Company" => Builders<HostMemoryEntity>.Sort.Descending(p => p.Company),
                        "Name" => Builders<HostMemoryEntity>.Sort.Descending(p => p.Name),
                        "Tag" => Builders<HostMemoryEntity>.Sort.Descending(p => p.Tag),
                        "Location" => Builders<HostMemoryEntity>.Sort.Descending(p => p.Location),
                        "Serial" => Builders<HostMemoryEntity>.Sort.Descending(p => p.Serial),
                        "Capacity" => Builders<HostMemoryEntity>.Sort.Descending(p => p.Capacity),
                        "Clock" => Builders<HostMemoryEntity>.Sort.Descending(p => p.Clock),
                        "Voltage" => Builders<HostMemoryEntity>.Sort.Descending(p => p.Voltage),
                        _ => null
                    },
                    _ => Builders<HostMemoryEntity>.Sort.Descending(p => p.Tag)
                });

            return new TableData<HostMemoryEntity>()
            {
                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<HostMemoryEntity>();
        }
    }
}