/**
 * @description 获取存储内容
 * @param { string } key
 * @returns { T | null }
 */
export const getLocalStorage = <T>(key: string): T | null => {
  try {
    const dataJSON = window.localStorage.getItem(key);
    if (!dataJSON) {
      return null;
    }
    return JSON.parse(dataJSON);
  } catch (error) {
    console.error(`get key=${key} error, Error:${(error as Error).message}`);
    return null;
  }
};

/**
 * @description 写入存储内容
 * @param { string } key
 * @param { unknown } data
 * @returns { tSuccess }
 */
type tSuccess = boolean;
export const setLocalStorage = (key: string, data: unknown): tSuccess => {
  try {
    const strData = JSON.stringify(data);
    window.localStorage.setItem(key, strData);
    return true;
  } catch (error) {
    console.error(`set key=${key} error, Error:${(error as Error).message}`);
    return false;
  }
};

/**
 * @description 删除存储内容
 * @param { string } key
 * @returns { T | null }
 */
export const deleteLocalStorage = (key: string) => {
  try {
    window.localStorage.removeItem(key);
  } catch (error) {
    console.error(`delete key=${key} error, Error:${(error as Error).message}`);
  }
};

/**
 * @description  获取当前storage值的长度
 * @returns { number }
 */
export const getLocalStorageLength = () => window.localStorage.length;
