import { reactive, watch } from 'vue'
import storejs from 'store'
import { IMusicScore } from '/osmd-extended/src'
import qs from 'query-string'

export interface SettingState {
  sett: iSett
  eva: iEva
}

/* 基本设置 */
export type iSett = {
  /** 护眼模式 */
  eyeProtection: boolean
  /** 延迟检测 */
  tuning: boolean
  /** 摄像头 */
  camera: boolean
  /** 摄像头 透明度 */
  opacity: number
  /** 循环播放 */
  loop: boolean
  /** 显示指法 */
  fingering: boolean
  /** 播放频率 */
  hertz: number
  /**曲谱大小 */
  scoreSize: 'small' | 'middle' | 'large'
  /** 曲谱类型 */
  type: IMusicScore
  /** 是否固定调 */
  keySignature: boolean
  /** 自定义每行小节数开关 */
  openCustomNodule: boolean
  /** 自定义每行小节数开关 */
  customNoduleNum: number
}

export type IDifficulty = 'BEGINNER' | 'ADVANCED' | 'PERFORMER'

/* 评测设置 */
export type iEva = {
  /** 难度 */
  difficulty: IDifficulty
  /** 是否保存到相册 */
  save: boolean
  /** 开启伴奏*/
  mute: boolean
  /** 反应时间MS */
  reactionTimeMs: number
}

const search = qs.parse(location.search);
const saveSetting = storejs.get('setting')

let initState: SettingState = {
  sett: {
    eyeProtection: false,
    tuning: false,
    camera: false,
    opacity: 70,
    loop: true,
    fingering: true,
    hertz: 442,
    scoreSize: 'middle',
    type: 'staff',
    keySignature: false,
    openCustomNodule: true,
    customNoduleNum: 4,
  },
  eva: {
    difficulty: 'ADVANCED',
    save: false,
    mute: true,
    reactionTimeMs: 0
  },
}
if (saveSetting) {
  const customNoduleInfo = JSON.parse(localStorage.getItem('customNoduleInfo')) || []
  const matchMusic = customNoduleInfo.find((n: any) => n.id === search?.id)
  const defaultNum = matchMusic ? matchMusic.customNum : 4
  // 如果有保存的设置，则使用保存的设置
  // 酷乐秀强制440，评测时会重新按照此处配置计算频率
  initState.eva = { ...initState.eva, ...saveSetting.eva }
  initState.sett = { ...initState.sett, ...saveSetting.sett, ...{customNoduleNum: defaultNum} };

  (window as any).sett = initState.sett
}

const state: SettingState = reactive(initState)

watch(state, () => {
  storejs.set('setting', state)
})

export default state
