import AppConsts from '../appconst';
import { AuthStore } from '../stores';
import { get, remove, set } from './core/localstorage.service';
export class TokenService {
  static getInstance() {
    if (!TokenService.instance) {
      TokenService.instance = new TokenService();
    }
    return TokenService.instance;
  }
  async getToken() {
    let authUser = await get(AppConsts.AUTH_USER_LOCALSTORAGE);
    if (authUser && authUser.JWToken) {
      if (new Date(authUser.ExpiresOn).getTime() > new Date().getTime()) {
        return authUser.JWToken;
      }
    }
    return null;
  }
  async getAuthUser() {
    let authUser = await get(AppConsts.AUTH_USER_LOCALSTORAGE);
    if (authUser && authUser.JWToken) {
      if (new Date(authUser.ExpiresOn).getTime() > new Date().getTime()) {
        return authUser;
      }
    }
    return null;
  }
  getAuthUserSync() {
    let authUser = JSON.parse(localStorage.getItem(AppConsts.AUTH_USER_LOCALSTORAGE));
    if (authUser && authUser.JWToken) {
      if (new Date(authUser.ExpiresOn).getTime() > new Date().getTime()) {
        return authUser;
      }
    }
    return null;
  }
  getTokenSync() {
    let authUser = JSON.parse(localStorage.getItem(AppConsts.AUTH_USER_LOCALSTORAGE));
    if (authUser && authUser.JWToken) {
      if (new Date(authUser.ExpiresOn).getTime() > new Date().getTime()) {
        return authUser.JWToken;
      }
    }
    return null;
  }
  isAuthenticated() {
    try {
      let token = this.getTokenSync();
      if (!!token) {
        return true;
      }
    }
    catch (_a) {
      return false;
    }
  }
  async getTokenExpiry() {
    let authUser = await get(AppConsts.AUTH_USER_LOCALSTORAGE);
    if (!authUser) {
      return 0;
    }
    let timeDiff = 0;
    if (authUser.ExpiresOn) {
      timeDiff = new Date(authUser.ExpiresOn).getTime() - new Date().getTime();
    }
    return Math.max(0, timeDiff);
  }
  async saveAuthUser(authUser) {
    AuthStore.state.authUser = Object.assign({}, authUser);
    AuthStore.state.isAuthenticated = true;
    await set(AppConsts.AUTH_USER_LOCALSTORAGE, authUser);
  }
  async removeAuthUser() {
    AuthStore.state.authUser = null;
    AuthStore.state.isAuthenticated = false;
    await remove(AppConsts.AUTH_USER_LOCALSTORAGE);
  }
}
