import React, {Component} from 'react';
import RichTextEditor, {createEmptyValue} from 'react-rte';
import {convertToRaw} from 'draft-js';
import autobind from 'class-autobind';
import { browserHistory } from 'react-router'
import type {EditorValue} from './RichTextEditor';

type Props = {};
type State = {
  value: EditorValue;
  readOnly: boolean
};

export default class LinkEdit extends Component {
  props: Props;
  state: State;

  constructor(props) {
    super(props);
    autobind(this);
    this.state = {
      value: createEmptyValue(),
      readOnly: false
    };

  }

  componentWillUpdate(){
  }

  componentDidUpdate(){
      if (this.props.results.insert === 1) {
        browserHistory.push("/");
      }
  }

  render() {
    let {value} = this.state;

    return (
      <div className="editor-demo">
  
        <div className="row">
          <RichTextEditor
            value={value}
            onChange={this._onChange}
            className="react-rte-demo"
            placeholder="Tell a story"
            toolbarClassName="demo-toolbar"
            editorClassName="demo-editor"
            readOnly={this.state.readOnly}
          />
        </div>
        <div className="row btn-row">
          <input ref="title" type="text" className="form-control login" placeholder="请输入标题"/>
          <input ref="en_title" type="text" className="form-control login" placeholder="请输入英文名字"/>
          <button type="button" onClick={this._onCommit} className="btn btn-primary btn-lg btn-block login">确定</button>
        </div>
      </div>
    );
  }

  _onCommit(){
    let content = this.state.value.toString('html');
    let title = this.refs.title.value;
    let en_title = this.refs.en_title.value;

    this.props.actions.insertBlog({en_title: en_title, title: title, content: content})
  }

  _logState() {
    let editorState = this.state.value.getEditorState();
    let contentState = window.contentState = editorState.getCurrentContent().toJS();
    console.log(contentState);
  }

  _logStateRaw() {
    let editorState = this.state.value.getEditorState();
    let contentState = editorState.getCurrentContent();
    let rawContentState = window.rawContentState = convertToRaw(contentState);
    console.log(JSON.stringify(rawContentState));
  }

  _onChange(value: EditorValue) {
    this.setState({value});
  }

  _onChangeSource(event: Object) {
    let source = event.target.value;
    let oldValue = this.state.value;
    this.setState({
      value: oldValue.setContentFromString(source, this.state.format),
    });
  }

  _onChangeFormat(event: Object) {
    this.setState({format: event.target.value});
  }

  _onChangeReadOnly(event: Object) {
    this.setState({readOnly: event.target.checked});
  }
}