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.Network.Routes;

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

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

            if (string.IsNullOrWhiteSpace(Search) is false)
            {
                var regex = new BsonRegularExpression(new Regex(Search, RegexOptions.IgnoreCase));
                filter &= Builders<HostInterfaceRouteEntity>.Filter.Regex(x => x.Destination, regex) |
                    Builders<HostInterfaceRouteEntity>.Filter.Regex(x => x.Mask, regex) |
                    Builders<HostInterfaceRouteEntity>.Filter.Regex(x => x.Gateway, regex) |
                    Builders<HostInterfaceRouteEntity>.Filter.Regex(x => x.Metric, regex) |
                    Builders<HostInterfaceRouteEntity>.Filter.Regex(x => x.Interfaces.First().Description, regex);
            }

            var query = Database.HostInterfaceRoute()
                .Aggregate()
                .Match(filter)
                .Lookup<HostInterfaceRouteEntity, HostInterfaceEntity, HostInterfaceRouteEntity>(Database.HostInterface(), p => p.Interface, p => p.Id, p => p.Interfaces)
                .Sort(state.SortDirection switch
                {
                    SortDirection.Ascending => state.SortLabel switch
                    {
                        "Destination" => Builders<HostInterfaceRouteEntity>.Sort.Ascending(p => p.Destination),
                        "Gateway" => Builders<HostInterfaceRouteEntity>.Sort.Ascending(p => p.Gateway),
                        "Mask" => Builders<HostInterfaceRouteEntity>.Sort.Ascending(p => p.Mask),
                        "Metric" => Builders<HostInterfaceRouteEntity>.Sort.Ascending(p => p.Metric),
                        "Interface" => Builders<HostInterfaceRouteEntity>.Sort.Ascending(p => p.Interfaces.First().Description),
                        _ => null
                    },
                    SortDirection.Descending => state.SortLabel switch
                    {
                        "Destination" => Builders<HostInterfaceRouteEntity>.Sort.Descending(p => p.Destination),
                        "Gateway" => Builders<HostInterfaceRouteEntity>.Sort.Descending(p => p.Gateway),
                        "Mask" => Builders<HostInterfaceRouteEntity>.Sort.Descending(p => p.Mask),
                        "Metric" => Builders<HostInterfaceRouteEntity>.Sort.Descending(p => p.Metric),
                        "Interface" => Builders<HostInterfaceRouteEntity>.Sort.Descending(p => p.Interfaces.First().Description),
                        _ => null
                    },
                    _ => Builders<HostInterfaceRouteEntity>.Sort.Ascending(p => p.Destination)
                });

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

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