import { environment } from '@/environment';
import { getApplicationLocation } from '@/utils/applPath';

export function b64_to_utf8(str: string): string {
  try {
    return decodeURIComponent(window.atob(str));
  } catch (ex) {
    console.log(`fail to decode "${str}"`);
    return '';
  }
}

export function utf8_to_b64(str: string): string {
  // remove unneeded "=" padding
  return window.btoa(encodeURIComponent(str)).replace('=', '');
}

/**
 * Request SSO connection
 */
export function hashLocalData(data?: string): string {
  if (
    !!data &&
    ![
      '',
      'null',
      'NULL',
      'undefined',
      '---',
      'unregistered',
      'unregistered/',
      'forbidden',
      'forbidden/',
    ].includes(data)
  ) {
    return utf8_to_b64(data);
  }
  const pathName = getApplicationLocation();
  if (['sso', '/sso', '/sso/'].includes(pathName)) {
    return utf8_to_b64('home');
  }
  if (
    !!pathName &&
    [
      '',
      'null',
      'NULL',
      'undefined',
      '---',
      'unregistered',
      'unregistered/',
      'forbidden',
      'forbidden/',
    ].includes(pathName)
  ) {
    return utf8_to_b64(pathName);
  }
  return utf8_to_b64('home');
}
/**
 * Request SSO connection
 */
export function unHashLocalData(data: string): string | undefined {
  if (!!data || ['', 'null', 'NULL', 'undefined', '---'].includes(data)) {
    return undefined;
  }
  try {
    return b64_to_utf8(data);
  } catch (ex) {
    console.error(`Can not convert the data: '${data}' ==> err=${ex}`);
  }
  return undefined;
}

export function parseToken(token: string): object {
  const cut = token.split('.');
  const decoded = b64_to_utf8(cut[1]);
  const jsonModel = JSON.parse(decoded);
  if (jsonModel.right === undefined) {
    return {};
  }
  if (jsonModel.right[environment.applName] === undefined) {
    return {};
  }
  return jsonModel.right[environment.applName];
}

/**
 * Request Open SSO Global website
 */
export function requestOpenSite(): void {
  window.location.href = environment.ssoSite;
}
/**
 * Request SSO connection
 */
export function requestSignIn(name?: string): void {
  console.log(
    `Request sign-in: '${environment.ssoSignIn}' + '${hashLocalData(name)}'`
  );
  window.location.href = environment.ssoSignIn + hashLocalData(name);
}
/**
 * Request SSO Disconnect
 */
export function requestSignOut(name?: string): void {
  const url = environment.ssoSignOut + hashLocalData(name);
  console.log(`Request just to the SSO: ${url}`)
  // unlog from the SSO
  window.location.href = url;
}
/**
 * Request SSO signUp
 */
export function requestSignUp(name?: string): void {
  const url = environment.ssoSignUp + hashLocalData(name);
  console.log(`Request just to the SSO: ${url}`)
  // unlog from the SSO
  window.location.href = url;
}
