'use strict';

const auth_store = require('./auth.store-1e630a7d.js');
const localstorage_service = require('./localstorage.service-6346a41d.js');

const AppConsts = {
  AUTH_USER_LOCALSTORAGE: "CurrentUser",
  userManagement: {
    defaultAdminUserName: 'admin',
  },
  localization: {
    defaultLocalizationSourceName: 'Test',
  },
  authorization: {
    encrptedAuthTokenName: 'enc_auth_token',
  }
};

class TokenService {
  static getInstance() {
    if (!TokenService.instance) {
      TokenService.instance = new TokenService();
    }
    return TokenService.instance;
  }
  async getToken() {
    let authUser = await localstorage_service.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 localstorage_service.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 localstorage_service.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) {
    auth_store.AuthStore.state.authUser = Object.assign({}, authUser);
    auth_store.AuthStore.state.isAuthenticated = true;
    await localstorage_service.set(AppConsts.AUTH_USER_LOCALSTORAGE, authUser);
  }
  async removeAuthUser() {
    auth_store.AuthStore.state.authUser = null;
    auth_store.AuthStore.state.isAuthenticated = false;
    await localstorage_service.remove(AppConsts.AUTH_USER_LOCALSTORAGE);
  }
}

exports.AppConsts = AppConsts;
exports.TokenService = TokenService;
