const LOCAL_STORAGE_USER_PREF_KEY = 'userPref';

export const useUserPref = () => {
  const saveUserPref = (
    key: string,
    value: any,
    path: string = 'global',
  ): void => {
    const userPref = getUserPrefFromLocalStorage();
    const pathPref = userPref[path] || {};
    pathPref[key] = value;
    userPref[path] = pathPref;
    setUserPrefFromLocalStorage(userPref);
  };

  const getUserPref = (key: string, path: string = 'global'): any => {
    const userPref = getUserPrefFromLocalStorage();
    const pathPref = userPref[path];
    if (!pathPref) {
      return undefined;
    }
    return pathPref[key] || undefined;
  };

  return {
    saveUserPref,
    getUserPref,
  };
};

export const getUserPrefFromLocalStorage = (): any => {
  try {
    return JSON.parse(
      localStorage.getItem(LOCAL_STORAGE_USER_PREF_KEY) || '{}',
    );
  } catch (e) {
    return {};
  }
};

export const setUserPrefFromLocalStorage = (userPref: any): void => {
  localStorage.setItem(LOCAL_STORAGE_USER_PREF_KEY, JSON.stringify(userPref));
};
