import React from 'react';
import PropTypes from 'prop-types';
import { Editor } from 'slate-react';
import { Value } from 'slate';
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';

const initialValueObject = {
  document: {
    nodes: [
      {
        object: 'block',
        type: 'paragraph',
        nodes: [
          {
            object: 'text',
            leaves: [
              {
                text: 'Start typing here.',
              },
            ],
          },
        ],
      },
    ],
  },
};
// Create our initial value...
const initialValue = Value.fromJSON(initialValueObject);
const isValueInitialValue = (value) => {
  if (!value || value.length === 0) {
    return false;
  }
  const valueParsed = JSON.parse(value);
  if (!valueParsed.document) {
    return false;
  }
  if (!valueParsed.document.nodes) {
    return false;
  }
  if (valueParsed.document.nodes.length === 0) {
    return false;
  }
  if (!valueParsed.document.nodes[0]) {
    return false;
  }
  if (!valueParsed.document.nodes[0].nodes) {
    return false;
  }
  if (valueParsed.document.nodes[0].nodes.length === 0) {
    return false;
  }
  if (!valueParsed.document.nodes[0].nodes[0]) {
    return false;
  }
  if (!valueParsed.document.nodes[0].nodes[0].leaves) {
    return false;
  }
  if (valueParsed.document.nodes[0].nodes[0].leaves.length === 0) {
    return false;
  }
  if (!valueParsed.document.nodes[0].nodes[0].leaves[0]) {
    return false;
  }
  if (!valueParsed.document.nodes[0].nodes[0].leaves[0].text) {
    return false;
  }
  if (valueParsed.document.nodes[0].nodes[0].leaves[0].text
    === initialValueObject.document.nodes[0].nodes[0].leaves[0].text) {
    return true;
  }
  return false;
};
// Define our app...
class RichTextEditor extends React.Component {
  // Set the initial value when the app is first constructed.
  constructor(props) {
    super(props);
    let startingValue;
    const { value } = props;
    if (props.value) {
      const parsedValue = JSON.parse(value);
      const slateValue = Value.fromJSON(parsedValue);
      startingValue = slateValue;
    } else {
      startingValue = initialValue;
    }
    this.first = true;
    this.state = {
      value: startingValue,
    };
    this.onChange = this.onChange.bind(this);
  }


  shouldComponentUpdate(nextProps) {
    const { value } = nextProps;
    console.log(value);
    console.log('1');
    if ((this.first && value.length > 0)
    || (isValueInitialValue(value))) {
      console.log('2');
      const valueParsed = JSON.parse(value);
      const slateValue = Value.fromJSON(valueParsed);
      this.setState({ value: slateValue });
      this.first = false;
    }
    return true;
  }

  // On change, update the app's React state with the new editor value.
  onChange({ value }) {
    const { isBuildMode } = this.props;
    if (isBuildMode && !isValueInitialValue(JSON.stringify(value))) {
      console.log(JSON.stringify(value));
      const { saveData } = this.props;
      this.setState({ value });
      saveData({ data: [{ data: JSON.stringify(value).toString(), attribute: 'value' }], groupId: 'value' });
    }
  }

  // Render the editor.
  render() {
    const { value } = this.state;
    return <Editor value={value} onChange={this.onChange} />;
  }
}
RichTextEditor.propTypes = {
  saveData: PropTypes.func.isRequired,
  isBuildMode: PropTypes.bool.isRequired,
};
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 (
                <RichTextEditor isBuildMode={isBuildMode} value={value} saveData={saveData} />
              );
            }}
          </GetWidgetData>
        )}
      </SaveWidgetData>
    )}
  </IsBuildMode>
);
