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 HostCreateDialog
{
    [Parameter] public EventCallback OnChanges { get; set; }

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

    private HostEntity? _model;

    public async Task ToggleAsync()
    {
        _model = new();
        _visible = !_visible;

        await InvokeAsync(StateHasChanged);
    }

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

        try
        {
            await Database.Host()
                .InsertOneAsync(new HostEntity
                {
                    Insert = DateTime.Now,
                    Name = _model.Name,
                    Description = _model.Description,
                }, cancellationToken: default)
                .ConfigureAwait(false);

            Notification.Success(Snackbar);

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