import localforage from "localforage";
const STORAGE = "storage";
const GET_SESSION_STORAGE = "getSessionStorage";
const SESSION_STORAGE = "sessionStorage";
const isSessionStorageEmpty = () => sessionStorage.length === 0;
const onStorageChange = (evt) => {
  if (evt.key === GET_SESSION_STORAGE) {
    localStorage.setItem(SESSION_STORAGE, JSON.stringify(sessionStorage));
    localStorage.removeItem(SESSION_STORAGE);
  } else if (evt.key === SESSION_STORAGE) {
    if (evt.newValue) {
      const sessionFromAnotherTab = JSON.parse(evt.newValue);
      if (sessionFromAnotherTab)
        Object.keys(sessionFromAnotherTab).forEach((key) => {
          sessionStorage.setItem(key, sessionFromAnotherTab[key]);
        });
    }
  }
};
const persistentStorage = {
  get: async (key) => localforage.getItem(key),
  set: async (key, value) => {
    await localforage.setItem(key, value);
  }
};
const listenStorageEvents = () => {
  window.addEventListener(STORAGE, onStorageChange);
  if (isSessionStorageEmpty())
    localStorage.setItem(GET_SESSION_STORAGE, `${Date.now()}`);
};
const removeStorageEvents = () => {
  window.removeEventListener(STORAGE, onStorageChange);
};
export {
  listenStorageEvents,
  persistentStorage,
  removeStorageEvents
};
