import { store } from "@tauri-store/valtio"
import { useSnapshot } from "valtio"
import { DEFAULT_STORE_CONFIG } from "./config"
import { enable, disable } from "@tauri-apps/plugin-autostart"
import { LazyStore } from '@tauri-apps/plugin-store';

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

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,
    setAutoStart,
    setStartHidden,
    setHiddenOnClose,
    resetAppStore,
  }
}

const launchStore = new LazyStore('cstb.json', { autoSave: true });
void launchStore.save()

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 setAutoStart = (autoStart: boolean) => {
  if (autoStart) {
    void enable()
  } else {
    void disable()
  }
  appStore.state.autoStart = autoStart
}

// 同步到 launchStore 使 start hidden 生效
const setStartHidden = async (startHidden: boolean) => {
  appStore.state.startHidden = startHidden;
  await launchStore.set('hidden', startHidden);
  await launchStore.save();
}

const setHiddenOnClose = (hiddenOnClose: boolean) => {
  appStore.state.hiddenOnClose = hiddenOnClose;
}

const resetAppStore = () => {
  setVersion(defaultValue.version)
  setHasUpdate(defaultValue.hasUpdate)
  setInited(defaultValue.inited)
  setNotice(defaultValue.notice)
  setUseMirror(defaultValue.useMirror)
  setAutoStart(defaultValue.autoStart)
  void setStartHidden(defaultValue.startHidden)
  setHiddenOnClose(defaultValue.hiddenOnClose)
}