import { StateStorage } from 'zustand/middleware'
import { Store } from "@tauri-apps/plugin-store"
// import { appConfigDir } from "@tauri-apps/api/path"
// import { useThrottleFn } from "@reactuses/core"
// import { create } from 'zustand'
// import { createJSONStorage, persist } from 'zustand/middleware'

// 节流设置
// const THROTTLE_TIME = 300
// const THROTTLE_TIME_STORE = 5000
// const THROTTLE_LEADING = false
// const THROTTLE_TRAILING = true

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

  const get = (key: string) => {
    return store.get(key)
  }

  console.log(store.path)

  const set = (key: string, value: unknown) => {
    // autoSave.run()
    setTimeout(async () => {
      await store.save()
    })
    return store.set(key, value)
  }

  // 自动保存
  // const autoSave = useThrottleFn(
  //   async () => {
  //     await store.save()
  //     // console.log("store saved")
  //   },
  //   THROTTLE_TIME,
  //   {
  //     'trailing': THROTTLE_TRAILING,
  //     'leading': THROTTLE_LEADING
  //   }
  // )

  // 自定义存储对象
  const storage: StateStorage = {
    getItem: async (name: string): Promise<string | null> => {
      console.log(name)
      return (await store.get(name)) || null
    },
    setItem: async (name: string, value: string): Promise<void> => {
      console.log(name, 'with value', value, 'has been saved')
      await store.set(name, value)
    },
    removeItem: async (name: string): Promise<void> => {
      console.log(name, 'has been deleted')
      await store.delete(name)
    },
  }

  return { store, get, set/* , autoSave */, storage }
}
