import { onMounted, onUnmounted } from "vue"

export const rhythmPracticeMes = () => {
  let resFun: (value: string) => void

  // 获取节奏练习设置
  function getRhythmPracticeSetting(rhythmPracticeRef?: HTMLIFrameElement): Promise<string> {
    return new Promise(res => {
      resFun = res
      if (rhythmPracticeRef) {
        rhythmPracticeRef.contentWindow?.postMessage({ api: "getTempoSetting" }, "*")
      } else {
        resFun("")
      }
    })
  }
  function handleMessage(event: any) {
    const { api, data } = event.data || {}
    if (api === "getTempoSetting") {
      const dataRes = data ? JSON.parse(data) : {}
      resFun(JSON.stringify(dataRes.setting) || "")
    }
  }

  onMounted(() => {
    window.addEventListener("message", handleMessage)
  })
  onUnmounted(() => {
    window.removeEventListener("message", handleMessage)
  })

  return {
    getRhythmPracticeSetting
  }
}
