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

namespace Insight.Web.Pages.Management.Hosts;

public partial class HostAgentDialog
{
    [CascadingParameter(Name = "Host")] public HostEntity? Host { get; set; }
    [Parameter] public EventCallback OnChanges { get; set; }

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

    private enum Content { Unassign, Assign }

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

        try
        {
            await Database.Host().UpdateOneAsync(Builders<HostEntity>
                .Filter.Eq(p => p.Id, Host.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;
        }
    }
}