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

namespace Insight.Web.Pages.Management.Scheduler.Tasks;

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

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

    private TaskEntity? _model;

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

        await InvokeAsync(StateHasChanged);
    }

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

        _model.Insert = DateTime.Now;

        try
        {
            await Database.Task()
                .InsertOneAsync(_model, 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
        {
            _visible = false;
        }
    }
}