using Insight.Infrastructure.Entities;
using Insight.Web.Constants;
using Microsoft.AspNetCore.Components;
using MongoDB.Driver;
using MudBlazor;

namespace Insight.Web.Pages.Management.Agents;

public partial class AgentHostDialog
{
    [Parameter] public EventCallback OnChanges { get; set; }

    [Inject] private IMongoDatabase Database { get; init; } = default!;
    [Inject] private ISnackbar Snackbar { get; init; } = default!;
    [Inject] private ILogger<AgentHostDialog> Logger { get; init; } = default!;

    private enum Content { Unassign, Assign }

    private AgentEntity? _model;

    public async void ToggleAsync(string? id)
    {
        if (id is null) return;

        try
        {
            _model = await Database.Agent()
                .Aggregate()
                .Match(Builders<AgentEntity>.Filter.Eq(p => p.Id, id))
                .Lookup<AgentEntity, HostEntity, AgentEntity>(Database.Host(), p => p.Id, p => p.Agent, p => p.Hosts)
                .FirstOrDefaultAsync(default);

            _visible = !_visible;
        }
        catch (Exception)
        {
            Notification.Error(Snackbar);
        }

        await InvokeAsync(StateHasChanged);
    }

    private async Task UnassignAsync()
    {
        if (_model is null) return;

        try
        {
            await Database.Host().UpdateOneAsync(p => p.Agent == _model.Id, Builders<HostEntity>
                .Update.Set(p => p.Agent, null));

            Notification.Success(Snackbar);

            if (OnChanges.HasDelegate)
            {
                await InvokeAsync(async () =>
                {
                    await OnChanges.InvokeAsync(this);
                });
            }
        }
        catch (Exception ex)
        {
            Notification.Error(Snackbar);
            Logger.LogError(ex.ToString());
        }
        finally
        {
            _visible = false;
        }
    }
}