import secureLocalStorage from 'react-secure-storage';

window.addEventListener('beforeunload', () => {
  if (
    !window.performance.getEntriesByType('navigation')
      .map((nav: any) => nav.type).includes('reload')
  ) {
    try {
      localStorage.clear();
      secureLocalStorage.clear();
    } catch (err) {
      throw err;
    }
  }
}, false);

export const loadItem = (
  key: string,
  defaultItem: any = null,
  secure: boolean = false,
) => {
  try {
    let item: any = localStorage.getItem(key);

    if (secure) {
      item = secureLocalStorage.getItem(key);

      return item ? item : defaultItem;
    }

    return item ? JSON.parse(item) : defaultItem;
  } catch (err) {
    console.error(err);

    return defaultItem;
  }
};

export const saveItem = (
  key: string,
  item: any,
  secure: boolean = false,
  callback?: any
) => {
  try {
    callback && callback();

    return secure ?
      secureLocalStorage.setItem(key, item) :
      localStorage.setItem(key, JSON.stringify(item));
  } catch (err) {
    throw err;
  }
};

export const removeItem = (key: string, secure: boolean = false) => {
  try {
    return secure ?
      secureLocalStorage.removeItem(key) :
      localStorage.removeItem(key);
  } catch (err) {
    throw err;
  }
};
