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

interface LaunchOption {
  option: string
  name: string
}

export interface VideoSetting {
  width: number; // 分辨率宽度
  height: number; // 分辨率高度
  fullscreen: string; // 全屏
  vsync: string; // 垂直同步
  enhanceCharacterContrast: string; // 增强角色对比度
  cmaa2AntiAliasing: string; // CMAA2抗锯齿
  msaaAntiAliasing: string; // 多重采样抗锯齿
  globalShadowQuality: string; // 全局阴影效果
  dynamicShadows: string; // 动态阴影
  modelTextureDetail: string; // 模型/贴图细节
  textureFilteringMode: string; // 贴图过滤模式
  lightShadowDetail: string; // 光影细节
  particleDetail: string; // 粒子细节
  ambientOcclusion: string; // 环境光遮蔽
  hdr: string; // 高动态范围
  fidelityFxSuperResolution: string; // Fidelity FX 超级分辨率
}

const defaultValue = {
  launchOptions: [
    { option: "-novid -high -freq 144 -fullscreen", name: "" },
    { option: "-novid -high -w 1920 -h 1080 -freq 144 -sw -noborder", name: "" },
    { option: "-novid -high -freq 144 -fullscreen -allow_third_party_software", name: "" },
  ] as LaunchOption[],
  launchIndex: 0,
  powerPlan: 0,
  videoSetting: {
    width: 1920,
    height: 1080
  } as VideoSetting,
}

export const toolStore = store(
  "tool",
  { ...defaultValue },
  DEFAULT_STORE_CONFIG,
)

export const useToolStore = () => {
  void toolStore.start
  const state = useSnapshot(toolStore.state)

  return {
    state,
    store: toolStore,
    setLaunchOption,
    setLaunchOptions,
    setLaunchIndex,
    setPowerPlan,
    setVideoSetting,
    addLaunchOption,
    resetToolStore,
  }
}

const setLaunchOption = (option: LaunchOption, index: number) => {
  toolStore.state.launchOptions = [
    ...toolStore.state.launchOptions.slice(0, index),
    option,
    ...toolStore.state.launchOptions.slice(index + 1),
  ]
}

const setLaunchOptions = (options: LaunchOption[]) => {
  toolStore.state.launchOptions = options
}

const setLaunchIndex = (index: number) => {
  toolStore.state.launchIndex = index
}

const setPowerPlan = (plan: number) => {
  toolStore.state.powerPlan = plan
}

const setVideoSetting = (setting: VideoSetting) => {
  toolStore.state.videoSetting = setting
}

const addLaunchOption = (option: LaunchOption) => {
  // 限制最高10个
  if (toolStore.state.launchOptions.length >= 10) {
    return
  }
  toolStore.state.launchOptions = [...toolStore.state.launchOptions, option]
}

const resetToolStore = () => {
  setLaunchOptions(defaultValue.launchOptions)
  setLaunchIndex(defaultValue.launchIndex)
  setPowerPlan(defaultValue.powerPlan)
  setVideoSetting(defaultValue.videoSetting)
}
