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.Systems.Services;

[Route(Navigation.Inventory.Systems.Services.Hosts)]
public partial class Hosts
{
    [Parameter] public string? ServiceName { 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()
    {
        ServiceName = ServiceName?.UriEscape(true);

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

        if (string.IsNullOrWhiteSpace(ServiceName))
        {
            Notification.Error(Snackbar, "Not Found");
            NavigationManager.NavigateTo(Navigation.Inventory.Systems.Services.Index);
            return;
        }

        Title = $"Inventory » Service » {ServiceName} » Hosts｜Insight";
        Breadcrumbs.Add(new BreadcrumbItem(ServiceName, 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("processid", regex) |
                    Builders<BsonDocument>.Filter.Regex("account", regex) |
                    Builders<BsonDocument>.Filter.Regex("startmode", regex) |
                    Builders<BsonDocument>.Filter.Regex("delay", regex) |
                    Builders<BsonDocument>.Filter.Regex("state", regex);
            }

            var query = Database.HostService()
                .Aggregate()
                .Match(Builders<HostServiceEntity>.Filter.Eq(p => p.Name, ServiceName))
                .Lookup("host", "_host", "_id", "hosts")
                .Match(new BsonDocument("hosts", new BsonDocument
                {
                    { "$exists", true },
                    { "$ne", new BsonArray() }
                }))
                .Lookup("customer", "hosts._customer", "_id", "customers")
                .Project(new BsonDocument
                {
                    { "_id", 0 },
                    { "processid", 1 },
                    { "account", 1 },
                    { "startmode", 1 },
                    { "delay", 1 },
                    { "state", 1 },
                    { "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"),
                        "ProcessId" => Builders<BsonDocument>.Sort.Ascending("processid"),
                        "Account" => Builders<BsonDocument>.Sort.Ascending("account"),
                        "StartMode" => Builders<BsonDocument>.Sort.Ascending("startmode"),
                        "Delay" => Builders<BsonDocument>.Sort.Ascending("delay"),
                        "State" => Builders<BsonDocument>.Sort.Ascending("state"),
                        _ => null
                    },
                    SortDirection.Descending => state.SortLabel switch
                    {
                        "Customer" => Builders<BsonDocument>.Sort.Descending("customer.name"),
                        "Host" => Builders<BsonDocument>.Sort.Descending("host.name"),
                        "ProcessId" => Builders<BsonDocument>.Sort.Descending("processid"),
                        "Account" => Builders<BsonDocument>.Sort.Descending("account"),
                        "StartMode" => Builders<BsonDocument>.Sort.Descending("startmode"),
                        "Delay" => Builders<BsonDocument>.Sort.Descending("delay"),
                        "State" => Builders<BsonDocument>.Sort.Descending("state"),
                        _ => null
                    },
                    _ => Builders<BsonDocument>.Sort.Ascending("host.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("processid")]
        public int? ProcessId { get; set; }

        [BsonElement("account")]
        public string? Account { get; set; }

        [BsonElement("startmode")]
        public string? StartMode { get; set; }

        [BsonElement("delay")]
        public bool? Delay { get; set; }

        [BsonElement("state")]
        public string? State { get; set; }

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

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