import { typeById, ITypeContentItem } from '/src/constant/fingering-colexiu'
import { Fingering as IFingering } from '/src/music-sheet/fingering/types'
import getTypes from '/src/music-sheet/fingering/types'
import { formatFixedKey, getImageSize, useFingeringSrc } from '/src/music-sheet/fingering'
import detailState from '/src/pages/detail/state'
import runtime, * as RuntimeUtils from '/src/pages/detail/runtime'
import { reactive, Ref, ref } from 'vue'
import formatId from '../fingering/format-id'

export type FingeringStatus = 'init' | 'show' | 'hidden'

const fingeringWidth = ref(0)
const fingeringStatus: Ref<FingeringStatus> = ref('hidden')

const fingeringViewInfo = async (type: ITypeContentItem) => {
  // @ts-ignore
  const detail: ITypeContentItem = type
  // 该声部有指法情况
  if (detail) {
    const activeType: IFingering = await getTypes(detail.name)
    if (activeType) {
      const usedFixedKey = formatFixedKey(detail.name, detailState.fixedKey)
      const fullsrc = useFingeringSrc(activeType, detail.name, usedFixedKey.value)
      const { width, height } = await getImageSize(fullsrc.value)
      const containerHeight = document.getElementById('colexiu-detail-music-sheet')?.clientHeight || 0
      const w = runtime.evaluatingStatus ? 0 : width
      const scale = containerHeight / height
      fingeringWidth.value = containerHeight ? scale * w : w
      if (width) {
        fingeringStatus.value = 'show'
      }
      return reactive({
        width,
        height,
        scale,
        usedFixedKey: usedFixedKey.value,
        fullsrc: fullsrc.value,
        activeType,
        detail,
      })
    }
  } else {
    fingeringStatus.value = 'hidden'
  }
}

export const useFingering = async (code = '') => {
  const activeType = ref({})
  const detail = ref({})
  const res = await fingeringViewInfo(typeById[formatId(code)])
  // console.log("🚀 ~ code:", typeById[formatId(code)] , formatId(code))
  activeType.value = res?.activeType || {}
  detail.value = res?.detail || {}
  return [fingeringStatus, fingeringWidth, activeType, detail]
}
