using Insight.Infrastructure;
using Insight.Infrastructure.Entities;
using Insight.Web.Components.Containers;
using Insight.Web.Constants;
using Insight.Web.Extensions;
using Microsoft.AspNetCore.Components;
using MongoDB.Bson;
using MongoDB.Bson.Serialization;
using MongoDB.Bson.Serialization.Attributes;
using MongoDB.Driver;
using MongoDB.Driver.Linq;
using MudBlazor;
using System.Text.RegularExpressions;
using SortDirection = MudBlazor.SortDirection;

namespace Insight.Web.Pages.Inventory.Network.Addresses;

[Route(Navigation.Inventory.Network.Addresses.Hosts)]
public partial class Hosts
{
    [Parameter] public string? Address { 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 void OnInitialized()
    {
        Address = Address?.UriEscape(true);

        Breadcrumbs.Add(new BreadcrumbItem("Home", href: Navigation.Home));
        Breadcrumbs.Add(new BreadcrumbItem("Inventory", href: "#", true));
        Breadcrumbs.Add(new BreadcrumbItem("Addresses", href: Navigation.Inventory.Network.Addresses.Index));

        if (string.IsNullOrWhiteSpace(Address))
        {
            Notification.Error(Snackbar, "Not Found");
            NavigationManager.NavigateTo(Navigation.Inventory.Network.Addresses.Index);
            return;
        }

        Title = $"Inventory » Address » {Address} » Hosts｜Insight";
        Breadcrumbs.Add(new BreadcrumbItem(Address, href: "#", true));
        Breadcrumbs.Add(new BreadcrumbItem("Hosts", href: "#", true));
    }

    private async Task<TableData<ViewModel>> LoadDataAsync(TableState state)
    {
        try
        {
            var filter = Builders<BsonDocument>.Filter.Empty;

            if (string.IsNullOrWhiteSpace(Search) is false)
            {
                var regex = new BsonRegularExpression(new Regex(Search, RegexOptions.IgnoreCase));
                filter &= Builders<BsonDocument>.Filter.Regex("customer.name", regex) |
                    Builders<BsonDocument>.Filter.Regex("host.name", regex) |
                    Builders<BsonDocument>.Filter.Regex("interface", regex) |
                    Builders<BsonDocument>.Filter.Regex("mask", regex);
            }

            var query = Database.HostInterfaceAddress()
                .Aggregate()
                .Match(Builders<HostInterfaceAddressEntity>.Filter.Eq(p => p.Address, Address))
                .Lookup("host", "_host", "_id", "hosts")
                .Match(new BsonDocument("hosts", new BsonDocument
                {
                    { "$exists", true },
                    { "$ne", new BsonArray() }
                }))
                .Lookup("customer", "hosts._customer", "_id", "customers")
                .Lookup("host_if", "_interface", "_id", "interfaces")
                .Project(new BsonDocument
                {
                    { "_id", 0 },
                    { "mask", 1 },
                    { "interface", new BsonDocument("$first", "$interfaces") },
                    { "host", new BsonDocument("$first", "$hosts") },
                    { "customer", new BsonDocument("$first", "$customers") },
                })
                .Match(filter)
                .Sort(state.SortDirection switch
                {
                    SortDirection.Ascending => state.SortLabel switch
                    {
                        "Customer" => Builders<BsonDocument>.Sort.Ascending("customer.name"),
                        "Host" => Builders<BsonDocument>.Sort.Ascending("host.name"),
                        "Mask" => Builders<BsonDocument>.Sort.Ascending("mask"),
                        "Interface" => Builders<BsonDocument>.Sort.Ascending("interface.name"),
                        _ => null
                    },
                    SortDirection.Descending => state.SortLabel switch
                    {
                        "Customer" => Builders<BsonDocument>.Sort.Descending("customer.name"),
                        "Host" => Builders<BsonDocument>.Sort.Descending("host.name"),
                        "Mask" => Builders<BsonDocument>.Sort.Descending("mask"),
                        "Interface" => Builders<BsonDocument>.Sort.Descending("interface.name"),
                        _ => null
                    },
                    _ => Builders<BsonDocument>.Sort.Ascending("customer.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
    {
        [BsonElement("mask")]
        public string? Mask { get; set; }

        [BsonElement("interface")]
        public HostInterfaceEntity? Interface { get; set; }

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

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