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.Bson.Serialization;
using MongoDB.Bson.Serialization.Attributes;
using MongoDB.Driver;
using MudBlazor;
using System.Text.RegularExpressions;
using SortDirection = MudBlazor.SortDirection;

namespace Insight.Web.Pages.Monitoring.Maintenance.Drives;

[Route(Navigation.Monitoring.Maintenance.Drives.Index)]
public partial class Index
{
    [Inject] private IMongoDatabase Database { get; init; } = default!;
    [Inject] private ISnackbar Snackbar { 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()
    {
        Title = $"Monitoring » Maintenance » Drives｜Insight";
        Breadcrumbs.Add(new BreadcrumbItem("Home", href: Navigation.Home));
        Breadcrumbs.Add(new BreadcrumbItem("Monitoring", href: Navigation.Monitoring.Index));
        Breadcrumbs.Add(new BreadcrumbItem("Maintenance", href: Navigation.Monitoring.Maintenance.Index));
        Breadcrumbs.Add(new BreadcrumbItem("Drives", href: "#", true));
    }

    private async Task<TableData<ViewModel>> LoadDataAsync(TableState state)
    {
        try
        {
            var filter = Builders<HostDriveEntity>.Filter.Ne(p => p.Status, "OK");
            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("customer.name", regex) |
                    Builders<BsonDocument>.Filter.Regex("host.name", regex) |
                    Builders<BsonDocument>.Filter.Regex("name", regex) |
                    Builders<BsonDocument>.Filter.Regex("firmware", regex) |
                    Builders<BsonDocument>.Filter.Regex("serial", regex) |
                    Builders<BsonDocument>.Filter.Regex("status", regex);
            }

            var query = Database.HostDrive()
                .Aggregate()
                .Match(filter)
                .Lookup("host", "_host", "_id", "hosts")
                .Match(new BsonDocument("hosts", new BsonDocument("$size", 1)))
                .Lookup("customer", "hosts._customer", "_id", "customers")
                .Project<BsonDocument>(new BsonDocument
                {
                    { "_id", 1 },
                    { "name", 1 },
                    { "firmware", 1 },
                    { "serial", 1 },
                    { "size", 1 },
                    { "status", 1 },
                    { "customer", new BsonDocument("$first", "$customers") },
                    { "host", new BsonDocument("$first", "$hosts") }
                })
                .Match(search)
                .Sort(state.SortDirection switch
                {
                    SortDirection.Ascending => state.SortLabel switch
                    {
                        "Host" => Builders<BsonDocument>.Sort.Ascending("host"),
                        "Customer" => Builders<BsonDocument>.Sort.Ascending("customer"),
                        "Name" => Builders<BsonDocument>.Sort.Ascending("name"),
                        "Firmware" => Builders<BsonDocument>.Sort.Ascending("firmware"),
                        "Serial" => Builders<BsonDocument>.Sort.Ascending("serial"),
                        "Size" => Builders<BsonDocument>.Sort.Ascending("size"),
                        "Status" => Builders<BsonDocument>.Sort.Ascending("status"),
                        _ => null
                    },
                    SortDirection.Descending => state.SortLabel switch
                    {
                        "Host" => Builders<BsonDocument>.Sort.Descending("host"),
                        "Customer" => Builders<BsonDocument>.Sort.Descending("customer"),
                        "Name" => Builders<BsonDocument>.Sort.Descending("name"),
                        "Firmware" => Builders<BsonDocument>.Sort.Descending("firmware"),
                        "Serial" => Builders<BsonDocument>.Sort.Descending("serial"),
                        "Size" => Builders<BsonDocument>.Sort.Descending("size"),
                        "Status" => Builders<BsonDocument>.Sort.Descending("status"),
                        _ => null
                    },
                    _ => Builders<BsonDocument>.Sort.Ascending("status")
                });

            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
    {
        [BsonId]
        public ObjectId? Id { get; set; }

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

        [BsonElement("type")]
        public string? Type { get; set; }

        [BsonElement("firmware")]
        public string? Firmware { get; set; }

        [BsonElement("serial")]
        public string? Serial { get; set; }

        [BsonElement("size")]
        public long? Size { get; set; }

        [BsonElement("status")]
        public string? Status { get; set; }

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

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