import React from 'react'
import { getChildren, getAttributes, getTagName, isElement } from 'jsonml.js/lib/utils'
import Base from './Base'
import Demo from './Demo'

export default class Readme extends Base {
  static collector = nextProps => {
    return nextProps.data.README()
  }
  getCompliedLang = node => {
    if (!node || !isElement(node)) {
      return false
    }
    const lang = getAttributes(node) && getAttributes(node).lang
    return getTagName(node) === 'pre' && (lang === 'css' || lang === 'jsx') && lang
  }
  getSouceCode = element => {
    const div = document.createElement('div')
    div.innerHTML = element[1].highlighted
    return div.textContent || div.innerText
  }
  spiltByJsx = children => {
    return children.map((element, idx) => {
      const lang = this.getCompliedLang(element)
      if (lang) {
        return (
          <Demo
            key={`demo${idx}`}
            lang={lang}
            textNode={this.props.utils.toReactComponent(element)}
            sourceCode={this.getSouceCode(element)}
          >
            {lang === 'jsx' ? this.props.utils.toReactComponent(children[idx - 1]) : null}
          </Demo>
        )
      } else if (this.getCompliedLang(children[idx + 1]) === 'jsx') {
        return null
      } else {
        return this.props.utils.toReactComponent(element)
      }
    })
  }
  render () {
    const { utils, toc, content, style, description } = this.props
    const styleList = style && (Array.isArray(style) ? style : [style])
    return (
      <div className='main-wrapper'>
        <div className='main-container main-container-component'>
          <article className='markdown'>
            {styleList
              ? styleList.map((style, no) => <style key={no} dangerouslySetInnerHTML={{ __html: style }} />)
              : null}
            {!description
              ? null
              : utils.toReactComponent(['section', { className: 'markdown' }].concat(getChildren(description)))}
            {!toc || toc.length <= 2 ? null : <section className='toc'>{utils.toReactComponent(toc)}</section>}
            {this.spiltByJsx(getChildren(content))}
          </article>
        </div>
      </div>
    )
  }
}
