import React from 'react'
import {render, unmountComponentAtNode} from 'react-dom'
import {renderToStaticMarkup} from 'react-dom/server'
import {Transforms} from 'slate'
import PureEditor from '../editor/pure'

export type CustomText = {
  bold?: boolean
  italic?: boolean
  code?: boolean
  text: string
}

export type MentionElement = {
  type: 'mention'
  character: string
  children: CustomText[]
}

const RE_REMOVE_SLATE_DATA = /data-slate(-(\w+))+="(\w+)"/g
const RE_REMOVE_CONTENT_EDITABLE = /contenteditable="(\w+)"/g

// dom string 替换
const replaceHTML = (htmlString: string) => {
  return htmlString
    .replace(RE_REMOVE_SLATE_DATA, '')
    .replace(RE_REMOVE_CONTENT_EDITABLE, '')
    .replace(/data-gramm="false"/, '')
}

// 挂在节点的方式获取节点
const getContentHTML = async (value: Node[]): Promise<string> => {
  return new Promise(resolve => {
    if (typeof window === 'undefined') {
      resolve(renderToStaticMarkup(<PureEditor data={value} />))
    } else {
      const rootNode = document.createElement('div')
      render(<PureEditor data={value} />, rootNode, () => {
        resolve(rootNode.innerHTML)
        unmountComponentAtNode(rootNode)
      })
    }
  })
}

// slate 数据类型 -> dom html
export const value2html = async (value: Node[]) => {
  const contentHTML = replaceHTML(await getContentHTML(value))
  return `${contentHTML}`
}

// 插入@xx 组件
export const insertMention = (editor: any, character: any, text?: string) => {
  if (!character) return
  const mention: MentionElement = {
    type: 'mention',
    character,
    children: [{text: ' '}],
  }
  // console.error(mention, 'editor')
  Transforms.insertNodes(editor, mention)
  Transforms.move(editor)
}
