import PropTypes from 'prop-types';
import React from 'react';
import { EditorState, Entity, AtomicBlockUtils, RichUtils } from 'draft-js';

const $ = global.jQuery;

class ModalSource extends React.Component {
  constructor(props) {
    super(props);
    this.onClose = this.onClose.bind(this);
    this.onConfirm = this.onConfirm.bind(this);
    this.onConfirmAtomicBlock = this.onConfirmAtomicBlock.bind(this);
  }

  componentWillUnmount() {
    $(document.body).off('hidden.bs.modal', this.onClose);
  }

  onConfirm(data) {
    const { editorState, options, onUpdate } = this.props;
    const entityKey = Entity.create(options.type, 'MUTABLE', data);
    const nextState = RichUtils.toggleLink(editorState, editorState.getSelection(), entityKey);

    onUpdate(nextState);
  }

  onConfirmAtomicBlock(data) {
    const { editorState, options, onUpdate } = this.props;
    const entityKey = Entity.create(options.type, 'IMMUTABLE', data);
    const nextState = AtomicBlockUtils.insertAtomicBlock(editorState, entityKey, ' ');

    onUpdate(nextState);
  }

  onClose(e) {
    const { onClose } = this.props;
    e.preventDefault();

    onClose();
  }

  render() {
    return <div />;
  }
}

ModalSource.propTypes = {
  editorState: PropTypes.instanceOf(EditorState).isRequired,
  // eslint-disable-next-line
  options: PropTypes.object.isRequired,
  // eslint-disable-next-line
  entity: PropTypes.object,
  onUpdate: PropTypes.func.isRequired,
  onClose: PropTypes.func.isRequired,
};

ModalSource.defaultProps = {
  entity: null,
};

export default ModalSource;

@@ -81,16 +81,8 @@
 ate,
- Entity,
  Ato
@@ -588,33 +588,116 @@
 nst 
-entityKey = Entity
+contentState = editorState.getCurrentContent();%0A    const contentStateWithEntity = contentState
 .create
+Entity
 (opt
@@ -717,32 +717,104 @@
 UTABLE', data);%0A
+    const entityKey = contentStateWithEntity.getLastCreatedEntityKey();%0A
     const nextSt
@@ -1028,33 +1028,116 @@
 nst 
-entityKey = Entity
+contentState = editorState.getCurrentContent();%0A    const contentStateWithEntity = contentState
 .create
+Entity
 (opt
@@ -1159,32 +1159,104 @@
 UTABLE', data);%0A
+    const entityKey = contentStateWithEntity.getLastCreatedEntityKey();%0A
     const nextSt
@@ -1481,15 +1481,12 @@
 urn 
-%3Cdiv /%3E
+null
 ;%0A  
@@ -1581,38 +1581,8 @@
 ed,%0A
-  // eslint-disable-next-line%0A
   op
@@ -1621,38 +1621,8 @@
 ed,%0A
-  // eslint-disable-next-line%0A
   en

Update ModalSource to Draft.js 0.10 API