@namespace Oqtane.Modules.Admin.Profiles
@inherits ModuleBase
@inject IProfileService ProfileService
@inject IStringLocalizer<Index> Localizer

@if (_profiles == null)
{
    <p><em>@Localizer["Loading..."]</em></p>
}
else
{
    <ActionLink Action="Add" Security="SecurityAccessLevel.Admin" Text="Add Profile" ResourceKey="AddProfile" />

    <Pager Items="@_profiles">
        <Header>
            <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.ProfileId.ToString())" ResourceKey="EditProfile" /></td>
            <td><ActionDialog Header="Delete Profile" Message="@Localizer["Are You Sure You Wish To Delete {0}?", context.Name]" Action="Delete" Class="btn btn-danger" OnClick="@(async () => await DeleteProfile(context.ProfileId))" ResourceKey="DeleteProfile" /></td>
            <td>@context.Name</td>
        </Row>
    </Pager>
}

@code {
    private List<Profile> _profiles;

    public override SecurityAccessLevel SecurityAccessLevel => SecurityAccessLevel.Admin;

    protected override async Task OnParametersSetAsync()
    {
        await GetProfilesAsync();
    }

    private async Task DeleteProfile(int profileId)
    {
        try
        {
            await ProfileService.DeleteProfileAsync(profileId);
            await logger.LogInformation("Profile Deleted {ProfileId}", profileId);

            AddModuleMessage(Localizer["Profile Deleted"], MessageType.Success);

            await GetProfilesAsync();

            StateHasChanged();
        }
        catch (Exception ex)
        {
            await logger.LogError(ex, "Error Deleting Profile {ProfileId} {Error}", profileId, ex.Message);
            AddModuleMessage(Localizer["Error Deleting Profile"], MessageType.Error);
        }
    }

    private async Task GetProfilesAsync()
    {
        _profiles = await ProfileService.GetProfilesAsync(PageState.Site.SiteId);
    }
}
