@page "/GroupManagement"
<Modal @ref="modal" />
<ConfirmDialog @ref="dialog" />
@using Common.Dtos.Group
@using HushianWebApp.Components
@using HushianWebApp.Service
@using HushianWebApp.Services
@inject ILocalStorageService localStorageService;
@inject NavigationManager navigationManager;
@inject GroupService groupService;
<Button Color="ButtonColor.Success" Style="margin-bottom:10px"
        @onclick="async()=>{
        await modal.ShowAsync<ADDGroupComponent>(title,parameters:parameters);
        }">
    گروه جدید
</Button>

<Grid @ref="grid" TItem="Read_GroupDto"
      AllowSorting="true"
      Class="table table-hover"
      DataProvider="DataProvider"
      HeaderRowCssClass="bg-primary text-white bg-opacity-75 border-bottom-0"
      Responsive="true"
      AllowPaging="true"
      OnRowDoubleClick="OnRowClick"
      AllowRowClick=true>

    <GridColumns>
        <GridColumn HeaderTextAlignment="Alignment.Center" TextAlignment="Alignment.Center" TItem="Read_GroupDto" HeaderText="تصویر گروه">
            @if (context.img?.Length != 0)
            {
                <Image Class="rounded-circle mx-auto d-block" src="@GetImageSource(context.img)" height="25" width="25" alt="Uploaded Image" />
            }
            else
            {
                <Icon Name="IconName.People" Size="IconSize.x5" />
            }
        </GridColumn>
        <GridColumn HeaderTextAlignment="Alignment.Center" TextAlignment="Alignment.Center" TItem="Read_GroupDto" HeaderText="شناسه گروه" SortKeySelector="item => item.ID">
            @context.ID
        </GridColumn>

        <GridColumn HeaderTextAlignment="Alignment.Center" TextAlignment="Alignment.Center" TItem="Read_GroupDto" HeaderText="نام گروه" SortKeySelector="item => item.Name">
            @context.Name
        </GridColumn>

        <GridColumn HeaderTextAlignment="Alignment.Center" TextAlignment="Alignment.Center" TItem="Read_GroupDto" HeaderText="توضیحات">
            @context.Info
        </GridColumn>

        <GridColumn HeaderTextAlignment="Alignment.Center" TextAlignment="Alignment.Center" TItem="Read_GroupDto" HeaderText="وضعیت">
            <Switch Value="@context.Available" ValueExpression="() => context.Available" ValueChanged="async(v)=>await SwitchChanged(context,v)" />

        </GridColumn>
        <GridColumn HeaderTextAlignment="Alignment.Center" TextAlignment="Alignment.Center" TItem="Read_GroupDto" HeaderText="عملیات">
            <Button Color="ButtonColor.Danger" Size="ButtonSize.ExtraSmall" @onclick="async()=>await DeleteGroup(context.ID,context.Name)"> حذف </Button>
            <Button Color="ButtonColor.Warning" Size="ButtonSize.ExtraSmall" @onclick="async()=>await showGroupsComponent(context.ID,context.Name)"> کاربران </Button>

        </GridColumn>
    </GridColumns>

</Grid>

@code {
    private ConfirmDialog dialog = default!;

    Dictionary<string, object> parameters = new Dictionary<string, object>();
    Grid<Read_GroupDto> grid = default!;
    private Modal modal = default!;
    string title = "گروه جدید";
    public List<Read_GroupDto> list = new();
    private async Task<GridDataProviderResult<Read_GroupDto>> DataProvider(GridDataProviderRequest<Read_GroupDto> request)
    {
        if (list.Count <= 0)
            list = await groupService.GetGroupsCompany();

        int skip = (request.PageNumber - 1) * request.PageSize;

        return await Task.FromResult(request.ApplyTo(list != null ? list.Skip(skip).Take(request.PageSize).ToList() : new()));
    }
    protected override async Task OnInitializedAsync()
    {
        parameters.Add("OnMultipleOfThree", EventCallback.Factory.Create(this, CallBack));

        if (await localStorageService.GetItem<string>("C/Role") != "Company")
            navigationManager.NavigateTo("/NotFound");
        await base.OnInitializedAsync();
    }
    private async Task OnRowClick(GridRowEventArgs<Read_GroupDto> args)
    {
        Dictionary<string, object> eparameters = new Dictionary<string, object>();
        eparameters.Add("model", new Update_GroupDto()
            {
                ID = args.Item.ID,
                img = args.Item.img,
                Info = args.Item.Info,
                Name = args.Item.Name
            });
        eparameters.Add("OnMultipleOfThree", EventCallback.Factory.Create(this, CallBack));


        await modal.ShowAsync<UpdateGroupComponent>($"ویرایش گروه {args.Item.Name}", parameters: eparameters);


    }
    private async Task SwitchChanged(Read_GroupDto model, bool value)
    {
        if (model.Available != value)
        {
            if (await groupService.ChangeAvailableGroupFromManager(model.ID, value))
                model.Available = value;
        }


    }
    private async Task DeleteGroup(int GroupID, string name)
    {
        var confirmation = await dialog.ShowAsync(
           title: $"مطمئنی می‌خوای {name} حذف کنی؟",
           message1: "پس از حذف، نمی‌توان آن را به حالت اولیه برگرداند.",
           message2: "می‌خوای ادامه بدی؟", new ConfirmDialogOptions()
               {
                   YesButtonColor = ButtonColor.Danger,
                   YesButtonText = "بله",
                   NoButtonText = "نه !"
               });

        if (!confirmation) return;


        if (await groupService.DeleteGroupFromManager(GroupID))
        {
            list = await groupService.GetGroupsCompany();
            await grid.RefreshDataAsync();
        }
    }
    async Task CallBack()
    {
        await modal.HideAsync();
        list = await groupService.GetGroupsCompany();
        await grid.RefreshDataAsync();
    }
    private string GetImageSource(byte[]? img)
    {
        if (img != null)
        {
            return $"data:image/jpeg;base64,{Convert.ToBase64String(img)}";
        }
        return string.Empty;
    }
    async Task showGroupsComponent(int GroupID, string name)
    {
        Dictionary<string, object> eparameters = new Dictionary<string, object>();
        eparameters.Add("GroupID", GroupID);

        modal.Size = ModalSize.Small;
        await modal.ShowAsync<GroupUsersComponent>($"کارشناسان گروه {name}", parameters: eparameters);
    }
}