import { get, set, remove } from '../core/localstorage.service';
import { HttpService } from '../httpService';
import AppConsts from '../../appconst';
import { AuthStore } from "../../stores/auth.store";
export class AuthService {
  constructor() { }
  static getInstance() {
    if (!AuthService.instance) {
      AuthService.instance = new AuthService();
    }
    return AuthService.instance;
  }
  async authenticate(authenticationInput) {
    const headers = {
      'Content-Type': 'application/json',
    };
    let result = await HttpService.http.post('api/Account/Authenticate', authenticationInput, {
      headers: headers
    });
    if (result) {
      const authData = result.Data;
      const authUser = {
        Id: authData.Id,
        UserName: authData.UserName,
        Email: authData.Email,
        Roles: authData.Roles,
        IsVerified: authData.IsVerified,
        JWToken: authData.JWToken,
        IssuedOn: authData.IssuedOn,
        ExpiresOn: authData.ExpiresOn,
        RefreshToken: authData.RefreshToken,
        PhotoUrl: "",
        IsFacilitator: authData.Roles.indexOf("Facilitator") > 0
      };
      const expireDate = authenticationInput.RememberClient ? new Date(authUser.ExpiresOn) : undefined;
      sparkle.auth.setToken(authUser.JWToken, expireDate);
      //TODO: change authUser.JWToken to encrypted
      sparkle.utils.setCookieValue(AppConsts.authorization.encrptedAuthTokenName, authUser.JWToken, expireDate, sparkle.appPath);
      await set(AppConsts.AUTH_USER_LOCALSTORAGE, authUser);
      AuthStore.state.authUser = Object.assign({}, authUser);
      return authUser;
    }
  }
  async signOut() {
    await remove(AppConsts.AUTH_USER_LOCALSTORAGE);
    sessionStorage.clear();
    sparkle.auth.clearToken();
    AuthStore.state.authUser = null;
    AuthStore.state.isAuthenticated = false;
  }
  async getLocalAuthUser() {
    return get(AppConsts.AUTH_USER_LOCALSTORAGE);
  }
}
