@namespace Oqtane.Modules.Admin.Roles
@inherits ModuleBase
@inject IRoleService RoleService
@inject IStringLocalizer<Index> Localizer

@if (_roles == null)
{
    <p><em>@Localizer["Loading..."]</em></p>
}
else
{
    <ActionLink Action="Add" Text="Add Role" ResourceKey="AddRole" />

    <Pager Items="@_roles">
        <Header>
            <th style="width: 1px;">&nbsp;</th>
            <th style="width: 1px;">&nbsp;</th>
            <th style="width: 1px;">&nbsp;</th>
            <th>@Localizer["Name"]</th>
        </Header>
        <Row>
            <td><ActionLink Action="Edit" Parameters="@($"id=" + context.RoleId.ToString())" Disabled="@(context.IsSystem)" ResourceKey="Edit" /></td>
            <td><ActionDialog Header="Delete Role" Message="@Localizer["Are You Sure You Wish To Delete The {0} Role?", context.Name]" Action="Delete" Security="SecurityAccessLevel.Admin" Class="btn btn-danger" OnClick="@(async () => await DeleteRole(context))" Disabled="@(context.IsSystem)" ResourceKey="DeleteRole" /></td>
            <td><ActionLink Action="Users" Parameters="@($"id=" + context.RoleId.ToString())" ResourceKey="Users" /></td>
            <td>@context.Name</td>
        </Row>
    </Pager>
}

@code {
    private List<Role> _roles;

    public override SecurityAccessLevel SecurityAccessLevel => SecurityAccessLevel.Admin;

    protected override async Task OnParametersSetAsync()
    {
        if (UserSecurity.IsAuthorized(PageState.User, RoleNames.Host))
        {
            _roles = await RoleService.GetRolesAsync(PageState.Site.SiteId, true);
            _roles = _roles.Where(item => item.Name != RoleNames.Everyone).ToList();
        }
        else
        {
            _roles = await RoleService.GetRolesAsync(PageState.Site.SiteId);
        }
    }

    private async Task DeleteRole(Role role)
    {
        try
        {
            await RoleService.DeleteRoleAsync(role.RoleId);
            await logger.LogInformation("Role Deleted {Role}", role);
            StateHasChanged();
        }
        catch (Exception ex)
        {
            await logger.LogError(ex, "Error Deleting Role {Role} {Error}", role, ex.Message);
            AddModuleMessage(Localizer["Error Deleting Role"], MessageType.Error);
        }
    }
}
