import { ref } from 'vue'
import { getDuration } from '/src/pages/detail/helpers'
import runtime, * as RuntimeUtils from '/src/pages/detail/runtime'
import detailState from '/src/pages/detail/state'
import { postMessage } from '/src/helpers/native-message'

export const useMidi = (durationNum: number, midiUrl?: string) => {
  const initial = ref(false)
  if (midiUrl) {
    console.log('曲谱为midi,使用app播放')
    initial.value = true
    detailState.midiPlayIniting = true
    // 销毁播放器
    postMessage({
      api: 'cloudDestroy'
    })
    // 发送初始化信息
    postMessage({
      api: 'cloudDetail',
      content: {
        midi: midiUrl,
        denominator: getDuration(runtime.osmd).denominator,
        numerator: getDuration(runtime.osmd).numerator,
        originalSpeed: detailState.activeDetail.originalSpeed,
        interval: 50,
        duration: durationNum * 1000,
      }
    }, () => {
      detailState.midiPlayIniting = false
      initial.value = false
      if (midiUrl) {
        RuntimeUtils.changeMode('music')
      }
    })
    runtime.durationNum = durationNum
  }
  return {
    initial,
  }
}
