@using Common.Dtos.Exper
@using HushianWebApp.Service
@inject GroupService groupService;
@inject UserService userService;
@inject HushianWebApp.Services.ILocalStorageService localStorageService;
@if (!Spinnervisible)
{
    <div class="row">
        <div class="col-md-12 col-sm-12" style="margin-bottom:15px">
            <AutoComplete @bind-Value="ExperName"
                          TItem="Read_ExperDto"
            DataProvider="DataProvider"
                          PropertyName="FullName"
            Placeholder="جستجو در کاربران..."
                          OnChanged="(Read_ExperDto exper) => OnAutoCompleteChanged(exper)" />
        </div>
    </div>
    <SortableList TItem="Read_ExperDto"
    Data="Expers"
    Context="item"
    AllowSorting="false">
        <ItemTemplate>
            @item.FullName
            <Tooltip Title="گرفتن دسترسی" role="button">
                <Icon Name="IconName.Trash3" @onclick="async()=>{await UnJoin(item);}"></Icon>
            </Tooltip>
        </ItemTemplate>
    </SortableList>
}

<div class="d-flex justify-content-center">
    <Spinner Type="SpinnerType.Dots" Class="me-3" Color="SpinnerColor.Success" Visible="@Spinnervisible" />
</div>


@code {
    private string? ExperName;
    private bool Spinnervisible = false;

    [Parameter] public int GroupID { get; set; }
    public List<Read_ExperDto> Expers { get; set; }
    = new();
    public List<Read_ExperDto> CoExpers { get; set; }
    = new();
    protected override async Task OnParametersSetAsync()
    {
        Spinnervisible = true;
        Expers = await groupService.GetExpersFromGroupID(GroupID);
        Spinnervisible = false;
        await base.OnParametersSetAsync();
    }
}
@functions {
    private async Task<AutoCompleteDataProviderResult<Read_ExperDto>> DataProvider(AutoCompleteDataProviderRequest<Read_ExperDto> request)
    {
        CoExpers = await userService.GetExpersCompany();
        return await Task.FromResult(new AutoCompleteDataProviderResult<Read_ExperDto> { Data = CoExpers.Where(w => w.FullName.Contains(request.Filter.Value)), TotalCount = CoExpers.Count() });
    }

    private async Task OnAutoCompleteChanged(Read_ExperDto exper)
    {
        Spinnervisible = true;
        if (exper != null
            && !Expers.Any(a => a.ID == exper.ID)
             && await groupService.JoinExperToGroup(GroupID, exper.ID) )
            Expers.Add(exper);
        Spinnervisible = false;
    }
    async Task UnJoin(Read_ExperDto exper)
    {
        Spinnervisible = true;
        if (exper != null && await groupService.UnJoinExperToGroup(GroupID, exper.ID))
            Expers.Remove(exper);
        Spinnervisible = false;
    }
}