using CMSMicroservice.Protobuf.Protos.Role;
using Microsoft.AspNetCore.Components;

using Microsoft.JSInterop;

namespace BackOffice.Pages.AutoComplete;

public partial class RoleAutoComplete
{
    [Inject] public RoleContract.RoleContractClient RoleService { get; set; }
    [Parameter] public long? Value { get; set; }
    [Parameter] public string? Label { get; set; } = "نقش";
    [Parameter] public EventCallback<long?> ValueChanged { get; set; }
    private List<GetAllRoleByFilterResponseModel> _items = new();
    private GetAllRoleByFilterResponseModel _item;
    protected override async void OnParametersSet()
    {
        await base.OnParametersSetAsync();
        if (Value > 0)
        {
            var getAll = await RoleService.GetAllRoleByFilterAsync(new()
            {
                Filter = new()
                {
                    Id = Value
                },
                PaginationState = new()
                {
                    PageNumber = 1,
                    PageSize = 1
                }
            });
            if (getAll != null && getAll.Models != null && getAll.Models.Any())
            {
                _item = getAll.Models.First();
                StateHasChanged();
            }

        }
    }
    private async Task OnSelected(GetAllRoleByFilterResponseModel? model)
    {
        if (model == null)
        {
            _item = null;
            await ValueChanged.InvokeAsync(null);
        }
        else
        {

            _item = model;
            await ValueChanged.InvokeAsync(model.Id);
        }
    }
    private async Task<IEnumerable<GetAllRoleByFilterResponseModel>> Search(string value, CancellationToken token)
    {
        var getAll = await RoleService.GetAllRoleByFilterAsync(new()
        {
            Filter = new()
            {
                Title = value
            },
            PaginationState = new()
            {
                PageNumber = 1,
                PageSize = 9
            }
        });
        if (getAll != null && getAll.Models != null)
            _items = getAll.Models.ToList();

        return _items;

    }
}