using System;

using CommonHelpers.WASM;
using AFXUI;
using BookRegistry.Client.DB;

namespace BookRegistry.Client {

//**************************************************************************************************
public static class Session {
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
static UserAuthorizationService UA => Services.UserAuthorizationService;
//==================================================================================================

public static bool IsOpen => _UserInfo_ != null;
public static bool IsInAdminMode => IsOpen && UserInfo.IsAdministrator;

/// <exception cref="InvalidOperationException" />
public static ServiceUser_Info UserInfo =>
   _UserInfo_ ?? throw SessionNotOpenError;
/// <exception cref="InvalidOperationException" />
public static string UserName =>
   UserInfo.LoginName;
/// <exception cref="InvalidOperationException" />
public static string RoleName =>
   _RoleName_ ?? throw SessionNotOpenError;
/// <exception cref="InvalidOperationException" />
public static DateTime LoginTime =>
   _LoginTime_ ?? throw SessionNotOpenError;

//==================================================================================================

/// <exception cref="InvalidOperationException" />
public static void VerifyIsOpen()
{
   if ( !IsOpen )
      throw SessionNotOpenError;
}

public static void Open( ServiceUser_Info userInfo, string roleName, DateTime loginTime )
{
   _UserInfo_ = userInfo;
   _RoleName_ = roleName;
   _LoginTime_ = loginTime;
   DebugConsole.Print(
      "Session for \"{0}\" ({1}) has been opened at {2} (loc.).",
      UserName, roleName, loginTime );
}
public static void Close()
{
   _UserInfo_ = null;
   _RoleName_ = null;
   _LoginTime_ = null;
   UA.ResetTokens();
   DebugConsole.Print( "Session has been closed." );
}

//==================================================================================================

public static InvalidOperationException SessionNotOpenError =>
   new InvalidOperationException( "User session is not open." );

//==================================================================================================

static ServiceUser_Info? _UserInfo_;
static string? _RoleName_;
static DateTime? _LoginTime_;

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
} // Session
//**************************************************************************************************

} // BookRegistry.Client
