@using Newtonsoft.Json
@using Models.Identity
@inject ILoadingSpinner _LoadingSpinner
@inherits LayoutComponentBase



<div class="page">
    <div class="sidebar">
        <NavMenu/>
    </div>

    <main>

        <article class="content px-4">
            @Body
        </article>
    </main>
</div>
@code
{
    
    
        protected override async void OnAfterRender(bool firstRender)
    {
        if (firstRender)
            await CheckLogin();
        base.OnAfterRender(firstRender);
    }

    async Task CheckLogin()
    {
        Console.WriteLine("" + Statics.LastCheck);
        if (Statics.LastCheck.HasValue && DateTime.Now.Subtract(Statics.LastCheck.Value).TotalMinutes < 5)
        {
            Console.WriteLine("less than 5 minutes login check");
            base.OnInitialized();
            return;
        }
        Console.WriteLine("checking login...");
        Statics.LastCheck = DateTime.Now;
        var hasToken = await LocalStorage.ContainKeyAsync(Statics.LoginTokenKey);
        if (!hasToken)
            NavigationManager.NavigateTo("/login");
        else
        {
            var token = await LocalStorage.GetItemAsStringAsync(Statics.LoginTokenKey);
            var res = await _userUtils.CheckLogin();
            var result =
                JsonConvert.DeserializeObject<CheckLoginResponse>(
                    await res.Content.ReadAsStringAsync());        
            if (!res.IsSuccessStatusCode)
            {
                await _LoadingSpinner.HideLoading();
                await _sweetAlertService.ShowSwal(title: "", message: "Login Expired", SweetAlertIcon.Error);
                NavigationManager.NavigateTo("/login");
            }
            await _LoadingSpinner.HideLoading();
            Statics.CurrentLoginInfo = result;
            StateHasChanged();
        }
    }

    private async void SignOut()
    {
        await LocalStorage.RemoveItemAsync(Statics.LoginTokenKey);
        await LocalStorage.RemoveItemAsync(Statics.RefreshTokenKey);
        NavigationManager.NavigateTo("/login");
    }

}
