import config from '../../config'
import React from 'react'
import TinyMCE from 'react-tinymce'
import cx from 'classnames'
import Mention from './Mention'
import uuid from 'react-tinymce/lib/helpers/uuid'
var { array, func, string } = React.PropTypes

var editorConfig = {
  content_css: config.cssBundle,
  menubar: false,
  statusbar: false,
  plugins: ['paste', 'autolink', 'link'],
  paste_as_text: true,
  toolbar: 'bold italic | bullist numlist | link unlink',
  resize: true,
  relative_urls: false
}

export default class RichTextEditor extends React.Component {
  static propTypes = {
    onChange: func,
    className: string,
    mentionTemplate: func,
    mentionSelector: string,
    mentionChoices: array,
    mentionTypeahead: func
  }

  constructor (props) {
    super(props)
    this.editorId = uuid()
  }

  handleChange = event => {
    // use the standard property name
    event.target.value = event.target.getContent()
    return this.props.onChange(event)
  }

  setContent (text) {
    this.editor().setContent(text)
  }

  editor () {
    return window.tinymce.EditorManager.editors.find(e => e.id === this.editorId)
  }

  render () {
    var { className, mentionTemplate, mentionSelector, mentionChoices, mentionTypeahead } = this.props

    return <div className={cx('rich-text-editor', className)}>
      <TinyMCE config={editorConfig} id={this.editorId}
        onChange={this.handleChange}
        onSetContent={this.handleChange}/>

      <Mention template={mentionTemplate}
        mentionSelector={mentionSelector}
        choices={mentionChoices}
        typeahead={mentionTypeahead}
        editorId={this.editorId}/>
    </div>
  }
}

@@ -791,34 +791,507 @@
 ps)%0A
-    this.editorId = uuid()
+%0A    // this window check is a workaround for server rendering of a single-post%0A    // page. if we call uuid() on the server it keeps a single count for all%0A    // requests, but the client starts from 0 for each request.%0A    //%0A    // a different workaround would have to be implemented if we were to add%0A    // a server-rendered page that had two or more editors on it.%0A    if (typeof window !== 'undefined') %7B%0A      this.editorId = uuid()%0A    %7D else %7B%0A      this.editorId = 'react-tinymce-0'%0A    %7D
 %0A  %7D

add workaround for server-rendering single post page