import { Store } from "@tauri-apps/plugin-store"
import { throttle } from "throttle-debounce"
/* eslint-disable @typescript-eslint/no-unsafe-assignment */
import type { StateStorage } from "zustand/middleware"
// import { useThrottleFn } from '@reactuses/core';

// 节流设置
export const THROTTLE_TIME = 300
export const THROTTLE_TIME_STORE = 2000
export const THROTTLE_LEADING = true
export const THROTTLE_TRAILING = true

// 自定义Store覆盖get, set等方法，以适应tauri+zustand
export async function tauriStore(name: string) {
  const store = await Store.load(`${name || "store"}.settings.json`, {
    autoSave: THROTTLE_TIME_STORE,
  })

  const doSet = throttle(
    THROTTLE_TIME,
    async (key: string, value: unknown) => await store.set(key, value),
    {
      noTrailing: !THROTTLE_TRAILING,
      noLeading: !THROTTLE_LEADING,
    },
  )

  const set = (key: string, value: unknown) => {
    doSet(key, value)
  }

  const get = async (key: string) => await store.get(key)


  return { store, get, set }
}
