import {
  DEFAULT_STORAGE_NAMESPACE,
  getWebStorageKey,
  NAMESPACE_STORAGE_SEPARATOR_WEB,
} from "./storageWebUtils.web";

export function saveSync(
  key: string,
  value: string,
  namespace: string = DEFAULT_STORAGE_NAMESPACE
) {
  const storageWebKey = getWebStorageKey(key, namespace);

  return localStorage.setItem(storageWebKey, value);
}

export function getSync(
  key: string,
  namespace: string = DEFAULT_STORAGE_NAMESPACE
) {
  const storageWebKey = getWebStorageKey(key, namespace);

  return localStorage.getItem(storageWebKey);
}

export function getAllSync(namespace: string = DEFAULT_STORAGE_NAMESPACE) {
  const allItems = {};

  for (let i = 0; i < localStorage.length; i++) {
    const key = localStorage.key(i);

    if (key && key.startsWith(namespace + NAMESPACE_STORAGE_SEPARATOR_WEB)) {
      const itemKey = key.split(NAMESPACE_STORAGE_SEPARATOR_WEB)[1];
      allItems[itemKey] = localStorage.getItem(key);
    }
  }

  return allItems;
}

export function removeSync(
  key: string,
  namespace: string = DEFAULT_STORAGE_NAMESPACE
) {
  const storageWebKey = getWebStorageKey(key, namespace);

  return localStorage.removeItem(storageWebKey);
}
