import { store } from "@tauri-store/valtio"
import { useSnapshot } from "valtio"
import { DEFAULT_STORE_CONFIG } from "./config"

const defaultValue = {
  version: "0.0.1",
  hasUpdate: false,
  inited: false,
  notice: "",
  useMirror: true,
}

export const appStore = store("app", { ...defaultValue }, DEFAULT_STORE_CONFIG)

export const useAppStore = () => {
  void appStore.start
  const state = useSnapshot(appStore.state)

  return {
    state,
    store: appStore,
    setVersion,
    setHasUpdate,
    setInited,
    setNotice,
    setUseMirror,
    resetAppStore,
  }
}

const setVersion = (version: string) => {
  appStore.state.version = version
}
const setHasUpdate = (hasUpdate: boolean) => {
  appStore.state.hasUpdate = hasUpdate
}
const setInited = (inited: boolean) => {
  appStore.state.inited = inited
}
const setNotice = (notice: string) => {
  appStore.state.notice = notice
}
const setUseMirror = (useMirror: boolean) => {
  appStore.state.useMirror = useMirror
}

const resetAppStore = () => {
  setVersion(defaultValue.version)
  setHasUpdate(defaultValue.hasUpdate)
  setInited(defaultValue.inited)
  setNotice(defaultValue.notice)
  setUseMirror(defaultValue.useMirror)
}