@using Moonlight.App.Services.Sessions
@using Moonlight.App.Perms
@using Moonlight.App.Helpers
@using Moonlight.Shared.Components.Alerts

@inject IdentityService IdentityService
@inject NavigationManager NavigationManager

@if (Allowed)
{
    @ChildContent
}
else
{
    <NoPermissionAlert />
}

@code
{
    [CascadingParameter(Name = "TargetPageType")]
    public Type TargetPageType { get; set; }
    
    [Parameter]
    public RenderFragment ChildContent { get; set; }

    private bool Allowed = false;

    protected override Task OnParametersSetAsync()
    {
        var attributes = TargetPageType.GetCustomAttributes(true);
        var permAttrs = attributes
            .Where(x => x.GetType() == typeof(PermissionRequired))
            .Select(x => x as PermissionRequired)
            .ToArray();

        Allowed = true;

        foreach (var permissionRequired in permAttrs)
        {
            var permission = Permissions.FromString(permissionRequired!.Name);

            if (permission == null)
            {
                Allowed = false;
                break;
            }

            if (!IdentityService.Permissions[permission])
            {
                Allowed = false;
                break;
            }
        }

        if (!Allowed)
        {
            Logger.Warn($"{IdentityService.Ip} has tried to access {NavigationManager.Uri} without permission", "security");
        }
        
        return Task.CompletedTask;
    }
}
