export type FormatXMLResult = {
  xml: string
  speed: number
  partNames: string[]
}

/** 获取到xml前处理，添加额外的节拍 */
export const fillBeatXML = (xml: string): string => {
  if (!xml) return ''
  const xmlParse = new DOMParser().parseFromString(xml, 'text/xml')
  const measures = xmlParse.getElementsByTagName('measure')
  // let speed = -1
  let beats = -1
  let beatType = -1
  // 小节中如果没有节点默认为休止符
  for (const measure of Array.from(measures)) {
    if (beats === -1 && measure.getElementsByTagName('beats').length) {
      beats = parseInt(
        measure.getElementsByTagName('beats')[0].textContent || '4'
      )
    }
    if (beatType === -1 && measure.getElementsByTagName('beat-type').length) {
      beatType = parseInt(
        measure.getElementsByTagName('beat-type')[0].textContent || '4'
      )
    }
    const divisions = parseInt(
      measure.getElementsByTagName('divisions')[0]?.textContent || '256'
    )
    if (measure.getElementsByTagName('note').length === 0) {
      const forwardTimeElement = measure
        .getElementsByTagName('forward')[0]
        ?.getElementsByTagName('duration')[0]
      if (forwardTimeElement) {
        forwardTimeElement.textContent = '0'
      }
      measure.innerHTML += `
        <note>
          <rest measure="yes"/>
          <duration>${divisions * beats}</duration>
          <voice>1</voice>
          <type>whole</type>
        </note>`
    }
  }
  return new XMLSerializer().serializeToString(xmlParse)
}

export type FormatXMLInfo = {
  speed: number
  title: string
  composer: string
  partNames: string[]
}

/** 获取xml基本信息，标题，速度等信息 */
export const getXmlInfo = (xml: string): FormatXMLInfo => {
  const data: FormatXMLInfo = {
    /** 速度 */
    speed: 0,
    /** 标题 */
    title: '',
    /** 作曲人 */
    composer: '',
    /** 声部列表 */
    partNames: []
  }

  const xmlParse = new DOMParser().parseFromString(xml, 'text/xml')
  data.title = xmlParse.getElementsByTagName('work-title')[0]?.textContent || ''
  data.composer = xmlParse.getElementsByTagName('creator')[0]?.textContent || ''
  const measures = xmlParse.getElementsByTagName('measure')

  for (const item of Array.from(xmlParse.getElementsByTagName('part-name'))) {
    if (item.textContent) {
      data.partNames.push(item.textContent)
    }
  }

  for (const measure of Array.from(measures)) {
    const perMinute = measure.getElementsByTagName('per-minute')
    if (perMinute.length && perMinute[perMinute.length - 1]) {
      data.speed = parseFloat(
        perMinute[perMinute.length - 1].textContent || '0'
      )
      break
    }
  }
  return data
}

/** 解析xml */
export const formatXMLFile = (file: File): FormatXMLResult => {
  console.log(file)
  const reader = new FileReader()
  reader.onload = e => {
    console.log(e)
  }
  reader.readAsText(file)
  return {
    xml: '',
    speed: 0,
    partNames: []
  }
}
