import Storage, { LoadParams } from 'react-native-storage';
import AsyncStorage from '@react-native-async-storage/async-storage';

export const storageApp = new Storage({
  size: 1000,
  storageBackend: AsyncStorage,
  defaultExpires: null, // 不过期
  enableCache: true,
});
/**
 * 缓存一个键值对
 * @param key
 * @param value
 * @param expires
 */
export const saveItem = (key: string, value: any, expires?: number | null) =>
  storageApp.save({ key, data: value, expires });
/**
 * 获取一个键值对
 * @param key
 */
export const getItem = (key: string) => {
  return new Promise<string | undefined>(resolve => {
    storageApp
      .load<string>({ key, autoSync: true, syncInBackground: true })
      .then(data => resolve(data))
      .catch(() => resolve(undefined));
  });
};

/**
 * 删除一个键值对
 * @param key
 */
export const removeItem = (key: string) => storageApp.remove({ key });
/**
 * 获取批量键值对
 * @param params
 */
export const getAllItems = (params: LoadParams[]) =>{
  return new Promise<string[]>(resolve => {
    storageApp.getBatchData<string>(params)
      .then(data => resolve(data))
      .catch(() => resolve([]));
  });
};


export const saveAllItems = (
  params: {
    key: string;
    id?: string;
    data: any;
    expires?: number | null;
  }[],
) => Promise.all([params.map(item => storageApp.save(item))]);

export const removeAllItems = (params: string[]) =>
  Promise.all([params.map(item => storageApp.remove({ key: item }))]);

export const getAllKeys = () => {
  return AsyncStorage.getAllKeys();
};
