@page "/";
@using TIAMWebApp.Shared.Application.Interfaces
@using TIAMWebApp.Shared.Application.Models
@using TIAMWebApp.Shared.Application.Utility
@using Newtonsoft.Json
@using System.IdentityModel.Tokens.Jwt
@using TIAMWebApp.Shared.Application.Models.ClientSide
@using AyCode.Interfaces.StorageHandlers;
@using System.Globalization;
@inject NavigationManager NavManager
@inject IJSRuntime JSRuntime
@inject LogToBrowserConsole logToBrowserConsole
@inject IUserDataService UserDataService
@inject ISecureStorageHandler SecureStorageHandler
@inject ISessionService sessionService;
@inject HttpClient http;
<h3>AppLaunch</h3>

@{
    if (string.IsNullOrWhiteSpace(TrackingId))
    {
        TrackingId = "";
        <p>Loading...</p>
    }
    else
    {
        <p>Loading with trackingId: @TrackingId</p>
    }
}

Loading....

@code {

    [Parameter]
    public string TrackingId { get; set; }

    string userDetailsStr;
    string locale;

    protected async override Task OnInitializedAsync()
    {
        var (_userDetailStr, _locale) = await GetLocalSettings();

        userDetailsStr = _userDetailStr;

        if(_locale != null)
        {            
            locale = _locale;
            Culture = new CultureInfo(locale);
            logToBrowserConsole.LogToBC("Locale from settings: " + locale);
        }
        else
        {
            logToBrowserConsole.LogToBC("Default locale:" + Culture.Name);
        }

        logToBrowserConsole = new LogToBrowserConsole(JSRuntime);
        //wait for 5 seconds
        await Task.Delay(1000);                      
        
        if (!string.IsNullOrWhiteSpace(userDetailsStr))
        {
            logToBrowserConsole.LogToBC(userDetailsStr);
            var userBasicDetail = JsonConvert.DeserializeObject<UserBasicDetails>(userDetailsStr);

            var handler = new JwtSecurityTokenHandler();
            var jsontoken = handler.ReadToken(userBasicDetail?.AccessToken) as JwtSecurityToken;

            if(userBasicDetail!= null)
                Setting.UserBasicDetails = userBasicDetail;

            if (jsontoken?.ValidTo < DateTime.UtcNow)
            {
                logToBrowserConsole.LogToBC("Token needs to be refreshed");                
                bool isTokenRefreshed = await UserDataService.RefreshToken();

                if (isTokenRefreshed)
                {
                    logToBrowserConsole.LogToBC("Token refreshed");

                }
                else
                {
                    logToBrowserConsole.LogToBC("Couldn't refresh token");
                    SignOut();
                    NavManager.NavigateTo("/index");
                    return;
                }


            }
            else
            {
                logToBrowserConsole.LogToBC("Valid token found");

            }

            string _userId = jsontoken.Claims.First(claim => claim.Type == JwtRegisteredClaimNames.NameId).Value;
            string _email = jsontoken.Claims.First(claim => claim.Type == JwtRegisteredClaimNames.Email).Value;
            var user = await UserDataService.IsLoggedInAsync(Guid.Parse(_userId));
            sessionService.User = user;            
            logToBrowserConsole.LogToBC($"Saved user in db is: {user.DisplayName}, setting autenthicated state");
            sessionService.IsAuthenticated = true;
            NavManager.NavigateTo("/index");
        }
        else
        {
            logToBrowserConsole.LogToBC("No token stored yet");
            NavManager.NavigateTo("/index");
        }

    }

    public async Task<(string, string)> GetLocalSettings()
    {
        string userDetailsStr = await SecureStorageHandler.GetFromSecureStorageAsync(nameof(Setting.UserBasicDetails));
        string locale = await SecureStorageHandler.GetFromSecureStorageAsync(nameof(Setting.Locale));
        return (userDetailsStr, locale);
    }

    private void SignOut()
    {
        SecureStorageHandler.ClearAllSecureStorageAsync();
        sessionService.User = null;
        sessionService.IsAuthenticated = false;
    }

    CultureInfo Culture
    {
        get => CultureInfo.CurrentCulture;
        set
        {
            if (CultureInfo.CurrentCulture != value)
            {
                Thread.CurrentThread.CurrentCulture = value;
                Thread.CurrentThread.CurrentUICulture = value;
                CultureInfo.DefaultThreadCurrentCulture = value;
                CultureInfo.DefaultThreadCurrentUICulture = value;                
            }
        }
    }


}
