import {
  parseCookie,
  setCookie,
  UNIQUE_ID_COOKIE_NAME,
} from 'mweb/common/utils/cookie';

export function uniqueIDGenerator(length: number = 32): string {
  let possible =
    'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';

  let text = '';
  for (let i = 0; i < length; i++) {
    let index = Math.floor(Math.random() * possible.length);
    text += possible.charAt(index);
  }

  return text;
}

const SECONDS_IN_YEAR = 60 * 60 * 24 * 365;
const DEVICE_ID_MAX_AGE_IN_SECONDS = 10 * SECONDS_IN_YEAR;

export function getOrCreateDeviceID(length: number = 32): string {
  let deviceID = parseCookie(document.cookie)[UNIQUE_ID_COOKIE_NAME];
  if (!deviceID) {
    deviceID = uniqueIDGenerator(length);
    setCookie(
      UNIQUE_ID_COOKIE_NAME,
      deviceID,
      DEVICE_ID_MAX_AGE_IN_SECONDS,
      document,
    );
  }
  return deviceID;
}

const MW_SESSION_ID_KEY = 'mwSessionID';

export function getOrCreateSessionID(length: number = 32): string {
  let sessionID: string = '';
  if (typeof sessionStorage !== 'undefined') {
    sessionID = sessionStorage.getItem(MW_SESSION_ID_KEY) || '';
    if (!sessionID) {
      sessionID = uniqueIDGenerator(length);
      try {
        sessionStorage.setItem(MW_SESSION_ID_KEY, sessionID);
      } catch (e) {
        sessionID = '';
      }
    }
  }
  return sessionID;
}
