import { NodeData, Node } from '../types'
import { walk, nodeRichTextToTextWithWrap } from '../utils'



type GeneralizationType = Array<NodeData> | { text: string } | null

const getNodeText = (data: NodeData): string => {
  return data.richText ? nodeRichTextToTextWithWrap(data.text) : data.text
}

const getTitleMark = (level: number): string => {
  return new Array(level).fill('#').join('')
}

const getIndentMark = (level: number): string => {
  return new Array(level - 6).fill('   ').join('') + '*'
}

// 转换成markdown格式
export const transformToMarkdown = (root: Node): string => {
  let content = ''
  walk(
    root,
    null,
    (node: Node, parent: Node | null, isRoot: boolean, layerIndex: number) => {
      const level = layerIndex + 1
      if (level <= 6) {
        content += getTitleMark(level)
      } else {
        content += getIndentMark(level)
      }
      content += ' ' + getNodeText(node.data)
      // 概要
      const generalization = node.data.generalization
      if (Array.isArray(generalization)) {
        content += generalization.map(item => {
          return ` [${getNodeText(item)}]`
        })
      } else if (generalization && 'text' in generalization) {
        const generalizationText = getNodeText(generalization)
        content += ` [${generalizationText}]`
      }
      content += '\n\n'
      // 备注
      if (node.data.note) {
        content += node.data.note + '\n\n'
      }
    },
    () => { },
    true
  )
  return content
}