using CommunityToolkit.Maui.Alerts;
using CommunityToolkit.Mvvm.ComponentModel;

namespace GreadyPoang.Core;
public partial class BaseViewModel : ObservableObject
{
    [ObservableProperty]
    private bool isBusy;

    protected async Task RunAsyncCommand(Func<Task> action, string loadingMessage = null, string errorMessage = "Ett fel inträffade")
    {
        if (IsBusy) return;

        try
        {
            IsBusy = true;

            if (!string.IsNullOrWhiteSpace(loadingMessage))
                await Snackbar.Make(
                    message: loadingMessage,
                    duration: TimeSpan.FromSeconds(2),
                    action: null).Show();

            await action.Invoke();
        }
        catch (Exception ex)
        {
            await Snackbar.Make(
                message: $"{errorMessage}: {ex.Message}",
                duration: TimeSpan.FromSeconds(3),
                action: () => Console.WriteLine("Åtgärd vald")).Show();
        }
        finally
        {
            IsBusy = false;
        }
    }
}

