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


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


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

  // 自动保存
  const autoSave = throttle(
    THROTTLE_TIME_STORE,
    async () => {
      await store.save()
    },
    {
      noTrailing: !THROTTLE_TRAILING,
      noLeading: !THROTTLE_LEADING
    }
  )

  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)
    autoSave()
  }

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

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

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