import { SysStorage } from '@/Frameworks/SysStorage';

const useStorage = (storage: Storage) => {
  const setItem = <T>(key: SysStorage, value: T) => {
    storage.setItem(key, value ? JSON.stringify(value) : '');
  };

  const getItem = (key: SysStorage) => {
    let value: string = storage.getItem(key) || '';
    try {
      value = JSON.parse(value);
      return value;
    } catch {
      return value;
    }
  };

  const removeItem = (key: SysStorage) => {
    storage.removeItem(key);
  };

  const clearAll = () => {
    for (const key in storage) {
      if (key) {
        storage.removeItem(key);
      }
    }
  };
  return {
    setItem,
    getItem,
    removeItem,
    clearAll,
  };
};
const SessionService = useStorage(window.sessionStorage || sessionStorage);
const LocalService = useStorage(window.localStorage || sessionStorage);

export { SessionService, LocalService };
