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

namespace Insight.Web.Pages.Management.Hosts;

[Route(Navigation.Management.Hosts.AgentAssign)]
public partial class AgentAssign
{
    [Parameter] public string? HostId { get; set; }

    [Inject] private IMongoDatabase Database { get; init; } = default!;
    [Inject] private NavigationManager NavigationManager { get; init; } = default!;
    [Inject] private ISnackbar Snackbar { get; init; } = default!;

    private TableContainer<AgentEntity>? Container { get; set; }
    private string Title { get; set; } = Global.Name;
    private List<BreadcrumbItem> Breadcrumbs { get; } = new();
    private string? Search { get; set; }

    protected override async Task OnInitializedAsync()
    {
        if (string.IsNullOrWhiteSpace(HostId) || ObjectId.TryParse(HostId, out var hostId) is false)
        {
            Notification.Error(Snackbar, "Not Found");
            NavigationManager.NavigateTo(Navigation.Management.Hosts.Index);
            return;
        }

        var host = await Database.Host()
            .Aggregate()
            .Match(Builders<HostEntity>.Filter.Eq(p => p.Id, HostId))
            .Lookup<HostEntity, AgentEntity, HostEntity>(Database.Agent(), p => p.Agent, p => p.Id, p => p.Agents)
            .FirstOrDefaultAsync(default);

        if (host is null)
        {
            Notification.Error(Snackbar, "Not Found");
            NavigationManager.NavigateTo(Navigation.Management.Hosts.Index);
            return;
        }

        Title = $"Hosts » {host.Name} » Agent Assign｜Insight";
        Breadcrumbs.Add(new BreadcrumbItem("Home", href: Navigation.Home));
        Breadcrumbs.Add(new BreadcrumbItem("Hosts", href: Navigation.Management.Hosts.Index));
        Breadcrumbs.Add(new BreadcrumbItem(host.Name, href: Navigation.Management.Hosts.DetailsHref(HostId)));
        Breadcrumbs.Add(new BreadcrumbItem("Agent Assign", href: "#", true));
    }

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

            if (string.IsNullOrWhiteSpace(Search) is false)
            {
                var regex = new BsonRegularExpression(new Regex(Search, RegexOptions.IgnoreCase));
                filter &= Builders<AgentEntity>.Filter.Regex(x => x.Serial, regex) |
                    Builders<AgentEntity>.Filter.Regex(x => x.Hostname, regex);
            }

            var query = Database.Agent()
                .Aggregate()
                .Match(filter)
                .Lookup<AgentEntity, HostEntity, AgentEntity>(Database.Host(), p => p.Id, p => p.Agent, p => p.Hosts)
                .Match(Builders<AgentEntity>.Filter.Size(p => p.Hosts, 0))
                .Sort(state.SortDirection switch
                {
                    SortDirection.Ascending => state.SortLabel switch
                    {
                        "Serial" => Builders<AgentEntity>.Sort.Ascending(p => p.Serial),
                        "Hostname" => Builders<AgentEntity>.Sort.Ascending(p => p.Hostname),
                        _ => null
                    },
                    SortDirection.Descending => state.SortLabel switch
                    {
                        "Serial" => Builders<AgentEntity>.Sort.Descending(p => p.Serial),
                        "Hostname" => Builders<AgentEntity>.Sort.Descending(p => p.Hostname),
                        _ => null
                    },
                    _ => Builders<AgentEntity>.Sort.Ascending(p => p.Serial)
                });

            var countResult = await query.Count().FirstOrDefaultAsync(default);

            return new TableData<AgentEntity>()
            {
                TotalItems = countResult is null ? 0 : (int)countResult.Count,
                Items = await query.Skip(state.Page * state.PageSize).Limit(state.PageSize).ToListAsync(default)
            };
        }
        catch (Exception)
        {
            Notification.Error(Snackbar);
            return new TableData<AgentEntity>();
        }
    }

    private async Task OnAssignAsync(AgentEntity? model)
    {
        try
        {
            await Database.Host().UpdateOneAsync(Builders<HostEntity>
                .Filter
                .Eq(p => p.Id, HostId), Builders<HostEntity>
                .Update
                .Set(p => p.Agent, model.Id?.ToString()), cancellationToken: default);

            Container?.RefreshAsync();

            Notification.Success(Snackbar);
        }
        catch (Exception)
        {
            Notification.Error(Snackbar);
        }
        finally
        {
            NavigationManager?.NavigateTo(Navigation.Management.Hosts.DetailsHref(HostId));
        }
    }
}