/* @flow */

import React, { Component } from 'react';
import { Editor } from '../../../src';
import draftToHtml from 'draftjs-to-html';
import Menu from '../Menu';
import styles from './styles.css';

export default class Demo1 extends Component {

  state: any = {
    editorContent: undefined,
  };

  _onEditorChange: Function = (editorContent) => {
    this.setState({
      editorContent,
    });
  };

  _uploadImageCallBack: Function = (file) => new Promise(
      (resolve, reject) => {
        const xhr = new XMLHttpRequest;
        xhr.open('POST', 'https://api.imgur.com/3/image');
        xhr.setRequestHeader('Authorization', 'Client-ID 2e4ea711654893b');
        const data = new FormData;
        data.append('image', file);
        xhr.send(data);
        xhr.addEventListener('load', () => {
          const response = JSON.parse(xhr.responseText);
          resolve(response);
        });
        xhr.addEventListener('error', () => {
          const error = JSON.parse(xhr.responseText);
          reject(error);
        });
      }
    );

  render() {
    const { editorContent } = this.state;
    return (
      <div className={styles.demo3_root}>
        <Menu />
        <div className={styles.demo3_label}>
          Playground for react wysiwyg editors, toolbar is alwasy visible.
        </div>
        <div className={styles.demo3_editorWrapper}>
          <Editor
            toolbarClassName={styles.demo3_toolbar}
            wrapperClassName={styles.demo3_wrapper}
            editorClassName={styles.demo3_editor}
            onChange={this._onEditorChange}
            toolbarAlwaysVisible
            uploadImageCallBack={this._uploadImageCallBack}
          />
        </div>
        <textarea
          className={styles.demo3_content}
          value={draftToHtml(editorContent)}
        >
        </textarea>
      </div>
    );
  }
}
