
@using Common.Dtos.Group
@using HushianWebApp.Service
@inject GroupService groupService;

@if (!Spinnervisible)
{
    <div class="row">
        <div class="col-md-12 col-sm-12" style="margin-bottom:15px">
            <AutoComplete @bind-Value="GroupName"
                          TItem="Read_GroupDto"
                          DataProvider="DataProvider"
                          PropertyName="Name"
                          Placeholder="جستجو در گروه ها..."
                          OnChanged="(Read_GroupDto group) => OnAutoCompleteChanged(group)" />
        </div>
    </div>
    <SortableList TItem="Read_GroupDto"
                  Data="Groups"
                  Context="item"
                  AllowSorting="false">
        <ItemTemplate>
            @item.Name
            <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? GroupName;
    private bool Spinnervisible = false;

    [Parameter] public int ExperID { get; set; }
    public List<Read_GroupDto> Groups { get; set; }
    = new();
    public List<Read_GroupDto> CoGroups { get; set; }
    = new();
    protected override async Task OnParametersSetAsync()
    {
        Spinnervisible = true;
        Groups = await groupService.GetGroupsFromExperID(ExperID);
        Spinnervisible = false;
        await base.OnParametersSetAsync();
    }
}
@functions {
    private async Task<AutoCompleteDataProviderResult<Read_GroupDto>> DataProvider(AutoCompleteDataProviderRequest<Read_GroupDto> request)
    {
        CoGroups = await groupService.GetGroupsCompany();
        return await Task.FromResult(new AutoCompleteDataProviderResult<Read_GroupDto> { Data = CoGroups.Where(w => w.Name.Contains(request.Filter.Value)), TotalCount = CoGroups.Count() });
    }

    private async Task OnAutoCompleteChanged(Read_GroupDto group)
    {
        Spinnervisible = true;
        if (group != null
            && !Groups.Any(a => a.ID == group.ID)
            && await groupService.JoinExperToGroup(group.ID, ExperID))
            Groups.Add(group);
        Spinnervisible = false;
    }
    async Task UnJoin(Read_GroupDto group)
    {
        Spinnervisible = true;
        if (group != null && await groupService.UnJoinExperToGroup(group.ID, ExperID))
            Groups.Remove(group);
        Spinnervisible = false;
    }
}