// 文档 https://localforage.docschina.org/
import localforage from 'localforage';

/**数据级缓存设置 */
export async function dbSet(storeName: string, key: string, value: any) {
  if (!storeName || !key || !value) {
    return false;
  }
  localforage.config({
    name: import.meta.env.VITE_APP_CODE,
    storeName: storeName,
  });
  try {
    await localforage.setItem(key, value);
    return true;
  } catch (error) {
    console.error(error);
  }
  return false;
}

/**数据级缓存获取 */
export async function dbGet(storeName: string, key: string) {
  if (!storeName || !key) {
    return null;
  }
  localforage.config({
    name: import.meta.env.VITE_APP_CODE,
    storeName: storeName,
  });
  let value: any = null;
  try {
    value = await localforage.getItem(key);
  } catch (error) {
    console.error(error);
  }
  return value;
}

/**数据级缓存全部移除 */
export async function dbClear(storeName: string) {
  if (!storeName ) {
    return false;
  }
  localforage.config({
    name: import.meta.env.VITE_APP_CODE,
    storeName: storeName,
  });
  try {
    await localforage.clear();
    return true;
  } catch (error) {
    console.error(error);
  }
  return false;
}

/**数据级缓存移除 */
export async function dbRemove(storeName: string, key: string) {
  if (!storeName || !key) {
    return false;
  }
  localforage.config({
    name: import.meta.env.VITE_APP_CODE,
    storeName: storeName,
  });
  try {
    await localforage.removeItem(key);
    return true;
  } catch (error) {
    console.error(error);
  }
  return false;
}

/**数据级缓存设置JSON */
export function dbSetJSON(storeName: string, key: string, jsonValue: object) {
  return dbSet(storeName, key, JSON.stringify(jsonValue));
}

/**数据级缓存获取JSON */
export async function dbGetJSON(storeName: string, key: string) {
  const value = await dbGet(storeName, key);
  if (typeof value === 'string') {
    return JSON.parse(value);
  }
  return value;
}
