import React from 'react';
import GetWidgetData from '@webaholics/one-app-core/client/OnePlugin/WidgetData/GetWidgetData';
import SaveWidgetData from '@webaholics/one-app-core/client/OnePlugin/WidgetData/SaveWidgetData';
import IsBuildMode from '@webaholics/one-app-core/client/LilJimmies/IsBuildMode';
import brace from 'brace';
import AceEditor from 'react-ace';

import 'brace/mode/jsx';
import 'brace/theme/monokai';
import 'brace/ext/language_tools';


// eslint-disable-next-line react/prefer-stateless-function
class CodeEditorView extends React.Component {
  constructor(props) {
    super(props);
    this.value = this.props.value;
    this.justSaved = false;
    this.onChange = this.onChange.bind(this);
  }

  shouldComponentUpdate(nextProps, nextState) {
    const { isBuildMode } = this.props;
    if (nextProps.isBuildMode !== isBuildMode) {
      this.value = nextProps.value;
      return true;
    }
    if (this.value !== nextProps.value) {
      if (this.value) {
        return false;
      }
      this.value = nextProps.value;
      return true;
    }
    return false;
  }

  onChange(e) {
    if (this.props.isBuildMode) {
      this.value = e;
      this.justSaved = true;
      this.props.saveData({ data: [{ data: e, attribute: 'value' }], groupId: 'value' });
    } else {
      this.forceUpdate();
    }
  }


  render() {
    return (
      <AceEditor
        readOnly={!this.props.isBuildMode}
        value={this.value}
        height="100%"
        width="100%"
        theme="monokai"
        mode="jsx"
        onChange={this.onChange}
        name="UNIQUE_ID_OF_DIV"
        editorProps={{ $blockScrolling: true }}
        // defaultValue="Just turn build mode on and start typing. Code is saved on key press."
        fontSize={16}
        enableLiveAutocompletion
        debounceChangePeriod={100}
        beautify
        spellcheck
      />
    );
  }
}
export default () => (
  <IsBuildMode>
    {isBuildMode => (

      <SaveWidgetData>
        {saveData => (
          <GetWidgetData>
            {(widgetData) => {
              let value = '';
              if (widgetData) {
                widgetData.forEach((data) => {
                  if (data.groupId === 'value' && data.attribute === 'value') {
                    value = data.data;
                  }
                });
              }
              return (
                <CodeEditorView isBuildMode={isBuildMode} value={value} saveData={saveData} />
              );
            }}
          </GetWidgetData>
        )}
      </SaveWidgetData>
    )}
  </IsBuildMode>
);
