@using CouchLog.Data
@using Microsoft.AspNetCore.Identity
@implements IDisposable

@inject NavigationManager NavigationManager
@inject AuthenticationStateProvider AuthenticationStateProvider
@inject UserManager<ApplicationUser> UserManager
@inject ApplicationDbContext CouchLogDB

<MudNavMenu>
    <MudNavLink Href="" Match="NavLinkMatch.All" Icon="@Icons.Material.Filled.Home">
        Home
    </MudNavLink>

    <MudNavLink Href="GlobalList" Icon="@Icons.Material.Filled.List">
        Globallist
    </MudNavLink>

    <MudNavLink Href="PrivateList" Icon="@Icons.Material.Filled.Lock">
        Privatelist
    </MudNavLink>

    <AuthorizeView Roles="Admin">
        <MudNavLink Href="AdminSettings" Icon="@Icons.Material.Filled.AdminPanelSettings">
            Admin Settings
        </MudNavLink>
    </AuthorizeView>

    <AuthorizeView>
        <Authorized>
            <MudDivider Class="my-2" />
            <MudNavLink Href="Account/Manage" Icon="@Icons.Material.Filled.Person">
                @context.User.Identity?.Name
            </MudNavLink>
            <form action="Account/Logout" method="post">
                <AntiforgeryToken />
                <input type="hidden" name="ReturnUrl" value="@currentUrl" />
                <MudNavLink Icon="@Icons.Material.Filled.Logout"
                            OnClick="@(() => { })"
                            Href="javascript:void(0)"
                            UserAttributes="@(new Dictionary<string, object>
                                { {"onclick", "this.closest('form').submit()"} })">
                    Logout                
                </MudNavLink>
            </form>
        </Authorized>
        <NotAuthorized>
            <MudDivider Class="my-2" />
            @if (_isRegistrationAllowed)
            {
                <MudNavLink Href="Account/Register" Icon="@Icons.Material.Filled.PersonAdd">
                    Register
                </MudNavLink>
            }
            <MudNavLink Href="Account/Login" Icon="@Icons.Material.Filled.Badge">
                Login
            </MudNavLink>
        </NotAuthorized>
    </AuthorizeView>

</MudNavMenu>

@code {
    private string? currentUrl;
    private bool _isRegistrationAllowed;

    protected override void OnInitialized()
    {
        currentUrl = NavigationManager.ToBaseRelativePath(NavigationManager.Uri);
        NavigationManager.LocationChanged += OnLocationChanged;
        _isRegistrationAllowed = CouchLogDB.AccountsSettings.First().IsRegistrationAllowed;
    }

    private void OnLocationChanged(object? sender, LocationChangedEventArgs e)
    {
        currentUrl = NavigationManager.ToBaseRelativePath(e.Location);
        StateHasChanged();
    }

    public void Dispose()
    {
        NavigationManager.LocationChanged -= OnLocationChanged;
    }
}