@namespace Oqtane.Modules.Admin.Roles
@inherits ModuleBase
@inject IRoleService RoleService

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

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

@code {
    private List<Role> _roles;

    public override SecurityAccessLevel SecurityAccessLevel => SecurityAccessLevel.Admin;

    protected override async Task OnParametersSetAsync()
    {
        _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("Error Deleting Role", MessageType.Error);
        }
    }
}
