@using Moonlight.Core.Services
@using Moonlight.Core.Attributes

@inject IdentityService IdentityService

@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()
    {
        // If this is missing, the 404 page would not be shown
        if (TargetPageType == null)
        {
            Allowed = true;
            return Task.CompletedTask;
        }
        
        var attributes = TargetPageType.GetCustomAttributes(true);
        
        var permissionAttributes = attributes
            .Where(x => x.GetType() == typeof(RequirePermissionAttribute))
            .Select(x => x as RequirePermissionAttribute)
            .Where(x => x != null)
            .ToArray();

        Allowed = true;

        // No permission to check? Then we are done
        if (permissionAttributes.Length == 0)
            return Task.CompletedTask;

        Allowed = false;

        foreach (var permissionRequired in permissionAttributes)
        {
            if(permissionRequired == null)
                continue;

            if (IdentityService.CurrentUser.Permissions >= permissionRequired.Level)
                Allowed = true;
        }

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