using CMSMicroservice.Protobuf.Protos.Role;
using Microsoft.AspNetCore.Components;
using MudBlazor;
using CMSMicroservice.Protobuf.Protos.User;
using CMSMicroservice.Protobuf.Protos.UserRole;

namespace BackOffice.Pages.User.Components;
public partial class UserRoleDialog
{
    [Parameter] public long UserId { get; set; }
    [CascadingParameter] IMudDialogInstance MudDialog { get; set; }
    MudForm _form;
    private bool _isLoading;
    private bool _isFirstLoad = true;
    [Inject] public RoleContract.RoleContractClient RoleService { get; set; }
    [Inject] public UserRoleContract.UserRoleContractClient UserRoleService { get; set; }
    private GetAllUserRoleByFilterResponse _userRoleresponse = new();
    private GetAllRoleByFilterResponse _roleresponse = new();
    private List<long> _selectedRole = new();
    protected override async Task OnInitializedAsync()
    {
        await base.OnInitializedAsync();

        _roleresponse = await RoleService.GetAllRoleByFilterAsync(new());
        _userRoleresponse = await UserRoleService.GetAllUserRoleByFilterAsync(new() { Filter = new() { UserId = UserId } });

        _selectedRole.AddRange(_userRoleresponse.Models.Select(s => s.RoleId));

        _isFirstLoad = false;
    }
    private async Task AddItem()
    {
        _isLoading = true;
        StateHasChanged();
        if (_userRoleresponse != null && _userRoleresponse.Models != null && _userRoleresponse.Models.Any())
        {
            foreach (var item in _userRoleresponse.Models)
            {
                await UserRoleService.DeleteUserRoleAsync(new() { Id = item.Id });

            }
        }
        foreach (var item in _selectedRole)
        {
            await UserRoleService.CreateNewUserRoleAsync(new() { UserId = UserId, RoleId = item });

        }

        _isLoading = false;
        StateHasChanged();

        MudDialog.Close(DialogResult.Ok(true));
    }
    private void OnChackedChange(bool check, long id)
    {
        if (check)
        {
            if (!_selectedRole.Any(x => x == id))
                _selectedRole.Add(id);
        }
        else
        {
            if (_selectedRole.Any(x => x == id))
                _selectedRole.Remove(id);
        }
    }
    void Cancel() => MudDialog.Cancel();
}