using Blazorise.DataGrid;
using FoodsharingSiegen.Contracts.Entity;
using FoodsharingSiegen.Server.Data.Service;
using Microsoft.AspNetCore.Components;

namespace FoodsharingSiegen.Server.Pages
{
    public partial class Users
    {
        ////////////////////////////////////////////////////////////////////////////////////////////////////
        /// <summary>   Gets or sets the user service. </summary>
        ///
        /// <value> The user service. </value>
        ////////////////////////////////////////////////////////////////////////////////////////////////////
        [Inject] public UserService UserService { get; set; } = null!;
        
        private List<User>? UserList { get; set; } 
        public DataGrid<User> UserDataGrid { get; set; }

        protected override async Task OnAfterRenderAsync(bool firstRender)
        {
            if (firstRender)
                await LoadUsers();
            
            await base.OnAfterRenderAsync(firstRender);
        }
        
        private async Task LoadUsers()
        {
            var usersR = await UserService.GetUsersAsync();
            if (usersR.Success) UserList = usersR.Data;
            
            await InvokeAsync(StateHasChanged);
        }

        private async Task RowUpdated(SavedRowItem<User, Dictionary<string, object>> arg)
        {
            if (arg.Item?.Id == null || arg.Item.Id.Equals(Guid.Empty) || arg.Values?.Any() != true) return;

            await UserService.Update(arg.Item);
        }

        private async Task RowInserted(SavedRowItem<User, Dictionary<string, object>> arg)
        {
            var addUserR = await UserService.AddUserAsync(arg.Item);
            if (!addUserR.Success)
            {
                // Error Toast
            }
            else
            {
                await LoadUsers();
            }
        }
    }
}