/**
 * app播放midi
 */

import { ref } from 'vue'
import { getDuration } from "/src/helpers/formateMusic";
import state, { onPlay } from "/src/state";
import { OpenSheetMusicDisplay } from "/osmd-extended/src";
import { api_cloudDestroy, api_cloudDetail, api_cloudVolume, api_cloudGetMediaStatus, 
  api_cloudPlay, api_cloudSuspend,  } from "/src/helpers/communication";
import { audioData } from "/src/view/audio-list"  

export type IMode = 'background' | 'music'

export const initMidi = (durationNum: number, midiUrl?: string) => {
  const initial = ref(false)
  if (midiUrl) {
    console.log('曲谱为midi,使用app播放')
    initial.value = true
    state.midiPlayIniting = true
    const duration: any = getDuration(state.osmd as unknown as OpenSheetMusicDisplay);
    // 销毁播放器
    api_cloudDestroy();
    // 发送初始化信息
    api_cloudDetail({
      api: 'cloudDetail',
      content: {
        midi: midiUrl,
        denominator: duration.denominator,
        numerator: duration.numerator,
        originalSpeed: state.originSpeed,
        interval: 50,
        duration: durationNum * 1000,
      }
    }, () => {
      state.midiPlayIniting = false
      initial.value = false
      if (midiUrl) {
        changeMode('music')
      }
    })
    state.durationNum = durationNum
  }
  return {
    initial,
  }
}

/** 获取当前MidiId */
export const getActiveMidiId = () => {
  return state.osmd?.sheet?.instruments?.[0]?.subInstruments?.[0]?.midiInstrumentID ?? 0
}

/**
 * 修改原音或伴奏
 * @param val IMode
 */
export const changeMode = async (val: IMode, type?: string | undefined) => {
  const cm: IMode = val === 'background' ? 'music' : 'background'
  console.log(!state.songs[val], val, cm)
  if (state.isAppPlay) {
    const data = new Map()
    for (const name of state.partListNames) {
      data.set(name, 60)
    }
    // for (const name of getVoicePartInfo().partListNames) {
    //   data.set(name, cm === 'background' ? 100 : 0)
    // }
    api_cloudVolume({
      activeMidiId: getActiveMidiId(),
      activeMidiVolume: cm === 'background' ? 100 : 0,
      parts: Array.from(data.keys()).map((item) => ({
        name: item,
        volume: data.get(item),
      })),
    })
  }
  state.playSource = val
  if (type === 'all') {
    state.audiosInstance?.setMute(true, state.songs[cm])
    state.audiosInstance?.setMute(true, state.songs[val])
  } else {
    state.audiosInstance?.setMute(true, state.songs[cm])
    state.audiosInstance?.setMute(false, state.songs[val])
  }
}

/**
 * 切换midi播放状态
 */
export const cloudToggleState = async () => {
  const cloudGetMediaStatus = await api_cloudGetMediaStatus();
  const status = cloudGetMediaStatus?.content.status
  if (status === 'init') {
    return
  }
  if (status === 'suspend') {
    await api_cloudPlay({
      songID: state.examSongId,
      startTime: audioData.progress * 1000,
      originalSpeed: state.originSpeed, // midi初始速度
      speed: state.speed, // 实际速度
      hertz: 440, //SettingState.sett.hertz,
    })
    // startCapture()
    onPlay()
  } else {
    await api_cloudSuspend({
      songID: state.examSongId,
    })
    // endCapture()
  }
  const cloudGetMediaStatused = await api_cloudGetMediaStatus()
  state.playState = cloudGetMediaStatused?.content.status
  console.log(cloudGetMediaStatused, 'cloudGetMediaStatused')
}