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.Scheduler.Tasks;

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

    private readonly List<BreadcrumbItem> _breadcrumbs = new();

    private TableContainer<ViewModel>? _container;
    private string _title = Global.Name;
    private string? _search;

    protected override void OnInitialized()
    {
        _title = "Tasks｜Insight";
        _breadcrumbs.Add(new BreadcrumbItem("Home", href: Navigation.Home));
        _breadcrumbs.Add(new BreadcrumbItem("Scheduler", href: Navigation.Management.Scheduler.Index));
        _breadcrumbs.Add(new BreadcrumbItem("Tasks", href: Navigation.Management.Scheduler.Tasks.Index, true));
    }

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

            if (string.IsNullOrWhiteSpace(_search) is false)
            {
                var regex = new BsonRegularExpression(new Regex(_search, RegexOptions.IgnoreCase));
                filter &= Builders<TaskEntity>.Filter.Regex(x => x.Name, regex);
            }

            var query = Database.Task()
                .Aggregate()
                .Match(filter)
                .AppendStage<BsonDocument>(new BsonDocument("$lookup", new BsonDocument
                {
                    { "from", "job_task" },
                    { "localField", "_id" },
                    { "foreignField", "_task" },
                    { "as", "jobs" }
                }))
                .AppendStage<BsonDocument>(new BsonDocument("$addFields",
                    new BsonDocument("jobs", new BsonDocument("$size", "$jobs"))
                ))
                .Sort(state.SortDirection switch
                {
                    SortDirection.Ascending => state.SortLabel switch
                    {
                        "Name" => Builders<BsonDocument>.Sort.Ascending("name"),
                        "Description" => Builders<BsonDocument>.Sort.Ascending("description"),
                        _ => null
                    },
                    SortDirection.Descending => state.SortLabel switch
                    {
                        "Name" => Builders<BsonDocument>.Sort.Descending("name"),
                        "Description" => Builders<BsonDocument>.Sort.Descending("description"),
                        _ => 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<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>();
        }
    }

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

    [BsonIgnoreExtraElements]
    private class ViewModel : TaskEntity
    {
        [BsonElement("jobs")]
        public int? Jobs { get; set; }
    }
}