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

namespace Insight.Web.Pages.Management.HostGroups;

[Route(Navigation.Management.HostGroups.Index)]
public partial class Index
{
    [Inject] private IMongoDatabase Database { get; init; } = default!;
    [Inject] private ISnackbar Snackbar { get; init; } = default!;

    private readonly string _title = "Host Groups｜Insight";
    private readonly List<BreadcrumbItem> _breadcrumbs = new();

    private TableContainer<IndexViewModel>? _container;
    private string? _search;

    protected override void OnInitialized()
    {
        _breadcrumbs.Add(new BreadcrumbItem("Home", href: Navigation.Home));
        _breadcrumbs.Add(new BreadcrumbItem("Host Groups", href: Navigation.Management.HostGroups.Index, true));
    }

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

            if (string.IsNullOrWhiteSpace(_search) is false)
            {
                var regex = new BsonRegularExpression(new Regex(_search, RegexOptions.IgnoreCase));
                search &= Builders<BsonDocument>.Filter.Regex("name", regex) |
                    Builders<BsonDocument>.Filter.Regex("description", regex);
            }

            var query = Database.HostGroup()
                .Aggregate()
                .Match(filter)
                .AppendStage<BsonDocument>(new BsonDocument("$lookup", new BsonDocument
                {
                    { "from", "hostgroup_host" },
                    { "localField", "_id" },
                    { "foreignField", "_hostgroup" },
                    //{ "pipeline", new BsonArray
                    //    {
                    //        new BsonDocument("$project", new BsonDocument
                    //        {
                    //            { "serial", 1 },
                    //            { "last_activity", 1 }
                    //        })
                    //    }
                    //},
                    { "as", "hosts" }
                }))
                .Project(new BsonDocument
                {
                    { "_id", 1 },
                    { "name", 1 },
                    { "description", 1 },
                    { "hosts", new BsonDocument("$size", "$hosts") }
                })
                //.AppendStage<BsonDocument>(new BsonDocument("$lookup", new BsonDocument
                //{
                //    { "from", "customer" },
                //    { "localField", "customer" },
                //    { "foreignField", "_id" },
                //    { "pipeline", new BsonArray
                //        {
                //            new BsonDocument("$project",
                //            new BsonDocument("name", 1))
                //        }
                //    },
                //    { "as", "customers" }
                //}))
                //.AppendStage<BsonDocument>(new BsonDocument("$project", new BsonDocument
                //{
                //    { "name", 1 },
                //    { "description", 1 },
                //    { "hosts", new BsonDocument("$first", "$agents") },
                //    { "customer", new BsonDocument("$first", "$customers") }
                //}))
                //.AppendStage<BsonDocument>(new BsonDocument("$addFields",
                //    new BsonDocument("online_diff",
                //    new BsonDocument("$subtract", new BsonArray
                //    {
                //        DateTime.Now,
                //        "$agent.last_activity"
                //    }))
                //))
                //.AppendStage<BsonDocument>(new BsonDocument("$addFields",
                //    new BsonDocument("online",
                //    new BsonDocument("$and", new BsonArray
                //    {
                //        new BsonDocument("$cond",
                //        new BsonArray
                //        {
                //            new BsonDocument("$isNumber",
                //            new BsonArray
                //            {
                //                "$online_diff"
                //            }), 1, 0
                //        }), new BsonDocument("$lt",
                //            new BsonArray
                //            {
                //                "$online_diff",
                //                10000
                //            })
                //    }))
                //))
                .Match(search)
                .Sort(state.SortDirection switch
                {
                    SortDirection.Ascending => state.SortLabel switch
                    {
                        "Name" => Builders<BsonDocument>.Sort.Ascending("name"),
                        "Description" => Builders<BsonDocument>.Sort.Ascending("description"),
                        "Hosts" => Builders<BsonDocument>.Sort.Ascending("hosts"),
                        _ => null
                    },
                    SortDirection.Descending => state.SortLabel switch
                    {
                        "Name" => Builders<BsonDocument>.Sort.Descending("name"),
                        "Description" => Builders<BsonDocument>.Sort.Descending("description"),
                        "Hosts" => Builders<BsonDocument>.Sort.Descending("hosts"),
                        _ => null
                    },
                    _ => Builders<BsonDocument>.Sort.Ascending("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<IndexViewModel>()
            {
                TotalItems = countResult is null ? 0 : (int)countResult.Count,
                Items = itemResult.Select(x => BsonSerializer.Deserialize<IndexViewModel>(x))
            };
        }
        catch (Exception)
        {
            Notification.Error(Snackbar);
            return new TableData<IndexViewModel>();
        }
    }

    private async Task OnRefreshAsync()
    {
        if (_container is null) return;
        await _container.RefreshAsync().ConfigureAwait(false);
    }

    [BsonIgnoreExtraElements]
    public class IndexViewModel
    {
        [BsonId]
        public ObjectId? Id { get; set; }

        [BsonElement("name")]
        public string? Name { get; set; }

        [BsonElement("description")]
        public string? Description { get; set; }

        [BsonElement("hosts")]
        public int? Hosts { get; set; }
    }
}